加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 获取或附加实体

发布时间:2020-12-15 20:58:01 所属栏目:百科 来源:网络整理
导读:我有以下方法: public bool RemoveBookCategories(IDictionaryBooks,IListC_Category books) { _context.Configuration.AutoDetectChangesEnabled = true; foreach (var book in books.Keys) { foreach (var category in books[book]) { if (!_context.Chan
我有以下方法:

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.”}

尽管我觉得这几乎是我试图避免在变换跟踪器中寻找实体.
我觉得我已经尝试了所有可以找到的解决方案,但没有任何效果: – /

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

解决方法

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

我打赌你在保存有一个或多个共同类别的书籍清单时遇到这个例外.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读