【发布时间】: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