我正在尝试更新一个附加了导航属性的实体。
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
...
}
当我只将实体插入数据库时,这很有效,但是当我更新时,我得到的错误是:
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.
我浏览了其他一些帖子,但给出的解决方案是:
将属性修改为非虚拟,即删除“虚拟”关键字。然而我的前辈说这不能被接受,因为这个类是自动生成的,一旦实体从数据库更新就会改变。
我们还有其他解决方案吗?
最佳答案
肯定是像 stock.Locations = myLocationCollection
这样的行导致了问题。您想要执行的操作如下:
stock.Locations.Clear();
foreach (var loc in myLocationsCollection)
stock.Locations.Add(loc);
这是一种解决方法,可用于将集合设置为一个整体。
关于c# - 无法设置类型的属性,因为集合已设置为 EntityCollection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23409004/