使用Entity Framework在循环pne中插入数据时出错

时间:2016-01-18 12:34:14

标签: entity-framework asp.net-mvc-4

在循环中插入记录 该物业" id"是对象关键信息的一部分,无法修改

 secProductionRepository.Add(tblSecProduction);
 this.SaveChanges();

CODE

Controller:这是我调用Repository方法的Controller代码。将数据添加到存储库并调用要插入的函数。我想我必须每次用new关键字初始化它。但我应该在哪里做。

SingleMaster objGetXMLData = _iSingleService.GetXMLData();
if (objGetXMLData._tblSecDoorXMLData != null)
{
    for (int totalCount = 0; totalCount < objGetXMLData._tblSecDoorXMLData.Count; totalCount++)
    {
        _tblSecDoorsProduction.txtTongue = singleDoorModel.txtTongue;
        _tblSecDoorsProduction.numFibMesh = Convert.ToInt32(singleDoorModel.chkBoxFibreMesh);
        _tblSecDoorsProduction.dteDesDate = DateTime.Now;
        _iSingleDoorService.UpdatetblSecDoorsProduction(_tblSecDoorsProduction, "Insert");
    }
}

存储库:我在这里插入新行

public void UpdatetblSecDoorsProduction(tblSecDoorsProduction  tblSecDoorsProduction, string Message)
{
    var secDoorsProductionRepository =   Nuow.Repository<tblSecDoorsProduction>();
    tblSecDoorsProduction alreadyAttached = null;
    if (Message == "Insert")
    {
        secDoorsProductionRepository.Add(tblSecDoorsProduction);
        Nuow.SaveChanges();
    }
}

1 个答案:

答案 0 :(得分:1)

每次在循环中创建新对象。这里更新了代码:

for (int totalCount = 0; totalCount < objGetXMLData._tblSecDoorXMLData.Count; totalCount++)
{
    tblSecDoorsProduction _tblSecDoorsProduction = new tblSecDoorsProduction();
    _tblSecDoorsProduction.txtTongue = singleDoorModel.txtTongue;
    _tblSecDoorsProduction.numFibMesh = Convert.ToInt32(singleDoorModel.chkBoxFibreMesh);
    _tblSecDoorsProduction.dteDesDate = DateTime.Now;
    _iSingleDoorService.UpdatetblSecDoorsProduction(_tblSecDoorsProduction, "Insert");
}