Reputation: 1230
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
Upvotes: 0
Views: 481
Reputation: 3032
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
Upvotes: 1