![](/img/trans.png)
[英]Insert Records in multiple table which are dependent on primary / foreign key using Linq-to-SQL
[英]Insert Multiple Records in Foreign key table - MVC
我正在尝试在具有外键列但无法在外键列中插入值的表中插入多个记录。 以下是表结构的屏幕截图:
我创建了一个表单,用户可以在其中使用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
上下文中插入AllocationsDetailedForecast
并将其与SalesExecutive
关联
forecast.SalesExecutive = db.SalesExecutive.Find(allocation.SalesExecutive_id);
它的上下文是db
。 尝试将forecast
添加到db
变量。 IEntityChangeTracker的多个实例无法引用实体对象中Pavel Shkleinik的检查答案。 在实体框架4.1中向实体添加相关对象时
编辑:
另外,确保此行中的forecastSetup
实体具有与forecast
相同的上下文:
forecast.AllocationsForecastSetup = forecastSetup
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.