I am trying to update an Entity which has navigation property attached to it.
public partial class Stock
{
#region Primitive Properties
public virtual int StockId
{
get;
set;
}
public virtual string StockName
{
get;
set;
}
#endregion
#region Navigation Properties
public virtual ICollection<Location> Locations
...
}
This works well when I just insert the entity in the Database, but when I update I get the error as:
An exception of type 'System.InvalidOperationException' occurred in EntityFrameworkDynamicProxies-Trade.Sales.Presentation.Admin but was not handled in user code
Additional information: The property 'Locations' on type 'Stock_4654D170FFCE308BB1B9AF1E2018476DF2E1C2E1DBA137F58AB96BCB9FAFC859' cannot be set because the collection is already set to an EntityCollection.
I went through some of the other posts, but the solution which is given is:
Modifying the properties as non-virtual i.e. Removing 'virtual' keyword. However my senior says this cannot be accepted as this class is generated automatically and will change once the Entity is updated from the DB.
Do we have any other solution for this to be worked ?
Definitely there is a line like stock.Locations = myLocationCollection
that is causing the problem. What you would like to do is the following:
stock.Locations.Clear();
foreach (var loc in myLocationsCollection)
stock.Locations.Add(loc);
It is a workaround that can be used to set the collection as a whole.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With