【问题标题】:Insert Multiple Records in Foreign key table - MVC在外键表中插入多条记录 - MVC
【发布时间】:2019-08-16 05:25:32
【问题描述】:

我正在尝试在具有外键列但无法在外键列中插入值的表中插入多条记录。 以下是表格结构的屏幕截图:

我创建了一个表单,用户可以在该表单中使用 Date/Variant 和 SalesExecutive 的某些组合在 AllocationsDetailedForecast 表中输入多条记录。只有 DealerQty 列对用户是可编辑的,而所有其他列都是只读的。

以下是我试图在数据库中保存值的控制器的代码:

  string allocationPeriod = allocation.AllocationMonth;

    AllocationsDetailedForecast forecast = new AllocationsDetailedForecast();
    forecast.ForecastDate = allocation.ForecastDate;

//****Here I'm trying to get the object of SalesExecutive by using the ID recieved from the View
        forecast.SalesExecutive = db.SalesExecutive.Find(allocation.SalesExecutive_id);
        forecast.VariantCode = allocation.VariantCode;            
        forecast.DealerQty = allocation.DealerQty;
        forecast.AllocationMonth = allocationPeriod;

        forecast.DealerName = dealerName;            
        forecast.AllocationsForecastSetup = forecastSetup;


      db.AllocationsDetailedForecast.Add(forecast);

插入记录时出现以下错误:

**System.InvalidOperationException: 'An entity object cannot be referenced by multiple instances of IEntityChangeTracker.'**

请帮我解决这个问题,如何在插入过程中将 salesExecutiveID 作为外键传递

【问题讨论】:

  • _uow 这个变量是从哪里来的?
  • 同一个实体对象在多个 dbContexts 中使用,您正在使用一个 db.SalesExecutive.Find(allocation.SalesExecutive_id); 和另一个可能在您的 uow 中,您应该通过 ùowRepository 加载 SalesExecutive 而不是直接在 dbContext 上
  • @DIlshodK 这是存储库参考,请看我的更新,我现在直接尝试添加对象仍然错误相同
  • @EhsanSajjad 请看我的更新,uow只是一个包含所有表的引用和一些通用函数的类,我现在直接尝试将对象添加到db,仍然错误相同
  • @AlinaAnjum forecast.AllocationsForecastSetup = forecastSetup 行呢? predictSetup 是否具有相同的上下文?

标签: c# asp.net asp.net-mvc entity-framework


【解决方案1】:

看来,您正在尝试在具有不同上下文的实体之间创建关联。您在_uow 上下文中插入AllocationsDetailedForecast 并将其与SalesExecutive 关联

forecast.SalesExecutive = db.SalesExecutive.Find(allocation.SalesExecutive_id);

它的上下文是db。尝试将您的 forecast 添加到 db 变量。在entity object cannot be referenced by multiple instances of IEntityChangeTracker. while adding related objects to entity in Entity Framework 4.1 中检查 Pavel Shkleinik 的答案

编辑:

另外,请确保forecastSetup 实体与此行中的forecast 具有相同的上下文:

forecast.AllocationsForecastSetup = forecastSetup

【讨论】:

  • 我试过db.AllocationsDetailedForecast.Add(forecast);,请看我的更新
  • 是的,这是上下文问题,fore predictsetup、salesexecutive 的上下文不同,谢谢
猜你喜欢
  • 2011-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-03
  • 1970-01-01
  • 2014-03-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多