【问题标题】:Many to many relationship in Entity Framework - results in “An entity object cannot be referenced by multiple instances of IEntityChangeTracker”实体框架中的多对多关系 - 导致“一个实体对象不能被多个 IEntityChangeTracker 实例引用”
【发布时间】:2015-11-12 03:48:37
【问题描述】:

我正在尝试在实体框架中设置一个经典的“文章和类别”场景。为此,我有这些课程:

public class RichContent : BaseIdEntity
{
    public string Headline { get; set; }

    public virtual List<RichContentCategory.RichContentCategory> Categories { get; set; }


    public RichContent()
    {
        Categories = new List<RichContentCategory.RichContentCategory>();
    }
}

还有我的类别:

public class RichContentCategory : BaseIdEntity
{
    public string Name { get; set; }
    public virtual List<RichContent.RichContent> RichContents { get; set; }

    public RichContentCategory()
    {
        this.RichContents = new List<RichContent.RichContent>();
    }
}

这是用这个设置的:

   modelBuilder.Entity<RichContent>()
                   .HasMany<RichContentCategory>(s => s.Categories)
                   .WithMany(c => c.RichContents)
                   .Map(cs =>
                   {
                       cs.MapLeftKey("RichContentRefId");
                       cs.MapRightKey("RichContentCategoryId");
                       cs.ToTable("RichContentCategoryPlacement");
                   });

现在,当我运行它并添加如下类别并保存时:

   item.Categories.Add(richContentCategory);

我在 CREATE 方法中的 _db.RichContent.Add(content); 处收到以下错误:

An unhandled exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll

Additional information: An entity object cannot be referenced by multiple instances of IEntityChangeTracker.

我可以理解潜在的问题是我需要如何使用相同的上下文。但是,我使用 Ninject 注入上下文,创建的服务如下所示:

 public class RichContentService : IRichContentService
    {
        private readonly Context _db;

        public RichContentService(Context db)
        {
            _db = db;
        }

        public RichContent Create(RichContent content)
        {
            _db.RichContent.Add(content);

            _db.SaveChanges();

            return GetById(content.Id);
        }
}

所以我的问题基本上是 - 在这种情况下,您如何为文章添加类别?

编辑:

我运行的代码是一个具有以下功能的导入器:

 finally
                {
                    if (needToCreate)
                    {
                        var result = Create(richContent);
                        logger.Info("Created a new rich-content page");
                    }
                }

还有 Create() 方法:

 public RichContent Create(RichContent content)
        {
            PerformValidation(content);

            _db.RichContent.Add(content);
            _db.SaveChanges();

            return GetById(content.Id);
        }

以及 CREATE 方法的输入:

 var item = new RichContent()
            {
                WordpressId = dto.id,
                DateCreated = dto.date,
                Slug = dto.slug,
                Content = dto.content,
                Headline = dto.title,
                DateModified = dto.modified,

            };

            if (dto.custom_fields.category_type != null && dto.custom_fields.category_type.Any() &&
               !string.IsNullOrEmpty(dto.custom_fields.category_type[0]))
            {
                var categories = _richContentCategoryService.GetBySpecification(new RichContentCategorySpecification()
                {
                    Take = Int32.MaxValue
                });

                var list = dto.custom_fields.category_type[0];
                foreach (var richContentCategory in categories)
                {

                    if (list.Contains(richContentCategory.WordpressName))
                    {
                        item.Categories.Add(richContentCategory);
                    }
                }
            }

            if (dto.custom_fields.featured != null)
            {
                item.Featured = dto.custom_fields.featured.Any(c => c == "1");
            }

            if (dto.custom_fields.area != null)
            {
                item.Area = dto.custom_fields.area.Any(c => c == "1");

                if (item.Area)
                {
                    var children = ConvertWordpressDtos(dto.children);
                    foreach (var child in children.Where(c=>c.Area))
                    {

                        child.Slug = string.Format("{0}/{1}", item.Slug, child.Slug);
                        item.Children.Add(child);
                    }
                }


            }

【问题讨论】:

  • 你从哪里得到RichContent?如果您从另一个上下文中获取实体,则可能会发生此错误。
  • @AlexSikilinda 我有一个小型导入器,它从不同的系统迭代很多节点,然后创建一个新资源(new RichContent())并调用 CREATE 方法
  • 能不能在构造RichContent的时候加上代码,传给Create?
  • @AlexSikilinda 所以我在 CREATE 方法内部而不是在外部创建实例?理论上,是的。我只是认为它的设计有点糟糕,并且与其他解决方案的工作方式不同。但它应该工作吗? :-)
  • 能否提供(new RichContent()) and call the CREATE的代码?

标签: c# entity-framework many-to-many entity-framework-6


【解决方案1】:

问题

异常清楚地表明,当您保存新的RichContent 时,与RichContent 关联的实体被另一个实体框架上下文跟踪。在您的特定情况下,实体是从_richContentCategoryService.GetBySpecification 返回的RichContentCategory:

var categories = _richContentCategoryService.GetBySpecification(new RichContentCategorySpecification()
{
    Take = Int32.MaxValue
});

var list = dto.custom_fields.category_type[0];
foreach (var richContentCategory in categories)
{
    if (list.Contains(richContentCategory.WordpressName))
    {
        item.Categories.Add(richContentCategory);
    }
}

如何解决

这里最好的选择是设法为在这种情况下使用的所有对象使用相同的上下文。为此,您可以将item 添加到类别中,然后使用_richContentCategoryService 保存类别:

var categories = _richContentCategoryService.GetBySpecification(new RichContentCategorySpecification()
{
    Take = Int32.MaxValue
});

var list = dto.custom_fields.category_type[0];
foreach (var richContentCategory in categories)
{
    if (list.Contains(richContentCategory.WordpressName))
    {
        richContentCategory.RichContents.Add(item);
    }
}

// Save updated categories somehow, using "_richContentCategoryService" object
_richContentCategoryService.Save(categories);

如果你做不到,你可以试试这样:

foreach (var richContentCategory in categories)
{
    if (list.Contains(richContentCategory.WordpressName))
    {
        item.Categories.Add(new RichContentCategory { Id = richContentCategory.Id});
    }
}

【讨论】:

  • 哇!你完全正确。它不仅有效,您还提供了很好的解释:) 谢谢。我会尽可能奖励赏金(约 4 小时)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-01
  • 2011-10-12
  • 1970-01-01
相关资源
最近更新 更多