如何一次创建多行?

时间:2017-04-19 13:48:37

标签: c# linq-to-sql asp.net-mvc-5.2

如何一次在桌面上创建多行? 我希望能够添加不存在的行,并在每次按提交时编辑/更新现有行。

为了测试这个,我只在数据库中创建了2个字段,似乎无法添加多行。

numofbuilding的值= 5。 只插入一行。

尝试:

public ActionResult CreateBuildings(Guid pi, int? numofbuilding)
{
    OnboardModel model = new OnboardModel();
    List<onboard_BuildingInfo> coms = new List<onboard_BuildingInfo>();

    for (int i = 1; i <= (numofbuilding+1); i++)
    { 
        onboard_BuildingInfo f = new onboard_BuildingInfo
        {
            projectID = pi,
            building_ID = i
        };
        coms.Add(f);
    }
    context.onboard_BuildingInfos.InsertAllOnSubmit(coms);
    context.SubmitChanges();
    return View(model);
}

并尝试:

public ActionResult CreateBuildings(Guid pi, int? numofbuilding)
{
    OnboardModel model = new OnboardModel();
    for (int i = 1; i <= numofbuilding; i++)
    { 
        onboard_BuildingInfo coms = new onboard_BuildingInfo
        {
            projectID = pi,
            building_ID = i
        };
        context.onboard_BuildingInfos.InsertOnSubmit(coms);
        context.SubmitChanges();
    }

    return View(model);
}

BuildingInfo-表

Create Table onboard_BuildingInfo (
        projectID                       UNIQUEIDENTIFIER DEFAULT        NEWID() ,
        building_ID                     int                 NULL ,  
        city_building                   varchar(500)        NULL ,
        numberofcommon                  INT                 NULL 
        PRIMARY KEY (projectID)
     )

1 个答案:

答案 0 :(得分:0)

使projectID不是主键,或在projectIDbuilding_ID上设置复合键。主键必须唯一,因此projectID列中不能包含重复项。复合键意味着(projectID * building_ID)的组合必须是唯一的,因此您可能在任一列中都有重复项,但不能同时包含两者。