繁体   English   中英

在外键表中插入多个记录-MVC

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM