c# - 无法设置类型的属性,因为集合已设置为 EntityCollection

标签 c# asp.net-mvc entity-framework entity

我正在尝试更新一个附加了导航属性的实体。

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/

相关文章:

entity-framework - Entity Framework 6 : Migration Drop column if exists

c# - 检查参数是否具有值的 MVC 操作属性?

c# - 分析 asp.net mvc 代码的最佳工具是什么?

c# - 仅当在 Ionos/1&1 托管上部署到生产环境时,尝试请求 API 时连接失败

c# 扩展一个表达式

c# - 具有多个参数的 "Bind"的 Ninject 语法

visual-studio-2008 - 刷新 Entity Framework 3.5中的存储过程

c# - 简单的 SELECT WHERE LINQ 查询列表

c# - UWP SQLite - 无法找到/创建 .db 文件

c# - 在 C# 中给出文件的路径