c# - 获取或附加实体

标签 c# sql-server entity-framework entity-framework-6

我有以下方法:

public bool RemoveBookCategories(IDictionary<Books, IList<C_Category>> books)
    {
        _context.Configuration.AutoDetectChangesEnabled = true;

        foreach (var book in books.Keys)
        {
            foreach (var category in books[book])
            {
                if (!_context.ChangeTracker.Entries<Books>().Any(e => e.Entity.BookId == book.BookId))
                    _context.Books.Attach(book);
                if (!_context.ChangeTracker.Entries<C_Category>().Any(e => e.Entity.Id == category.Id))
                    _context.C_Category.Attach(category);

                book.C_Category.Remove(category);
            }
        }

        if (_context.SaveChanges() > 0)
            return true;

        return false;
    }

它按预期工作.. 有时。 其他时候我收到此错误消息:

{"Attaching an entity of type 'DataAccess.Plusbog.C_Category' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate."}

虽然我觉得这几乎是我试图避免在 changetracker 中寻找实体的原因。 我觉得我已经尝试了我能找到的所有解决方案,但没有任何效果:-/

任何帮助将不胜感激:-)

最佳答案

仔细检查您附加的实体的导航属性:类别可能具有 Books 属性,该属性具有其他书籍,而这些书籍又具有其他类别。 EF 将遍历整个图并附加它可以到达的每个实体,从而产生上述问题。尝试清空一些您不需要处理的导航属性。

我敢打赌,您在保存具有一个或多个共同类别的图书列表时会遇到此异常。

关于c# - 获取或附加实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35058410/

相关文章:

c# - 应用程序代码中 try-catch block 无法捕获的异常

c# - ASP.NET 中缓存的 Request.IsAuthenticated 问题

mysql - 每个数据库提供程序类型允许的最大参数数是多少?

asp.net - web.config 中与 targetFramework 相关的配置错误

entity-framework - 无法使用 RIA 服务在客户端上加载相关实体

c# - 从 DataGrid 单元格复制文本

c# - 如何创建加载窗口?

sql - 从 SQL Server 表中获取连续数字范围

SQL Server Management Studio - 如何在不删除表的情况下更改字段类型

c# - 使用 LINQ 计算嵌套的导航表行