【发布时间】: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中,您应该通过ùow或Repository加载SalesExecutive而不是直接在 dbContext 上 -
@DIlshodK 这是存储库参考,请看我的更新,我现在直接尝试添加对象仍然错误相同
-
@EhsanSajjad 请看我的更新,uow只是一个包含所有表的引用和一些通用函数的类,我现在直接尝试将对象添加到db,仍然错误相同
-
@AlinaAnjum
forecast.AllocationsForecastSetup = forecastSetup行呢? predictSetup 是否具有相同的上下文?
标签: c# asp.net asp.net-mvc entity-framework