简体   繁体   中英

Insert Multiple Records in Foreign key table - MVC

I am trying to insert multiple records in a table who have Foreign Key column but unable to insert values in a foreign key column. Following is the screen shot of the table Structure:

在此处输入图片说明

I've created a form where user can enter multiple records in AllocationsDetailedForecast table with certain combinations of Date/Variant & SalesExecutive. Only DealerQty column is editable to the user while all others are being readonly.

Following is the code of my Controller where I am trying to Save Values in The database:

  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);

I am getting the following error while inserting the record:

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

Please Help me resolve this, How can I pass salesExecutiveID during Insertion as a Foreign key

It seems, you are trying to create association between entities with different contexts. You are inserting AllocationsDetailedForecast in _uow context and associating it with SalesExecutive

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

which its context is db . Try to add your forecast to db variable. Check answer of Pavel Shkleinik in entity object cannot be referenced by multiple instances of IEntityChangeTracker. while adding related objects to entity in Entity Framework 4.1

EDIT:

Also, make sure forecastSetup entity has the same context with forecast in this line:

forecast.AllocationsForecastSetup = forecastSetup

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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