如何使用Ado.net C#插入项目列表?

时间:2014-07-04 09:29:42

标签: c# sql ado.net

我有一个商店程序,其中包含2参数1st projectId和2nd Userid

但我必须使用单一连接将列表映射到该特定项目,但我无法弄清楚如何插入整个列表。

internal bool MapEmployeesToProject(int projectId, List<Users> lstUserToMap)
{
    int value = 0;
    bool check = true;
    SqlConnection conn = new SqlConnection(VSTMConfigurations.ConnectionString);

    using (conn)
    {
        SqlParameter[] param = new SqlParameter[2];
        param[0] = new SqlParameter("@ProjectId",projectId );
        param[1] = new SqlParameter("@ProjectDetails", );
        // if there is a single user than i could pass userid here 
        // i am phasing a problem how to pass whole listOfUsers

        using (SqlCommand cmd1 = CreateCommand(conn, param))
        {
            cmd1.CommandText = "sp_MapProject";
            try
            {
                conn.Open();
                SqlTransaction transaction = conn.BeginTransaction();
                cmd1.Transaction = transaction;
                try
                {
                    value = Convert.ToInt32(cmd1.ExecuteNonQuery());
                    if (value > 0)
                    {
                        transaction.Commit();
                        check = true;
                    }
                    else
                    {
                        transaction.Rollback();
                        check = false;
                    }
                }
                catch (Exception ex1)
                {
                    transaction.Rollback();
                    check = false;
                }
                finally
                {
                    transaction.Dispose();
                }
            }
            catch (Exception ex)
            {
                check = false;
            }
        }
    }
    return check;
}

商店程序

sp_MapProject
(@ProjectId int,@UserId int)
as
begin
     Insert into ProjectUsers values (@ProjectId,@UserId)
end
请帮忙!!

1 个答案:

答案 0 :(得分:0)

您可以使用projectIdUserid列在数据库中定义user define table type。然后,您可以使用DataTable将数据传递给存储过程。

e.g。 http://www.codeproject.com/Articles/412802/Sending-a-DataTable-to-a-Stored-Procedure

谢谢!