我有一个域模型,其中包含自有类型的收集。当我尝试在拥有的集合中添加多个对象时?我有一个例外:
system.invalidoperationException :'实体类型'childitem'的实例无法跟踪,因为另一个 具有键值'{nameId:-2147482647,id:0}'的实例已经在 跟踪。替换拥有的实体在不更改的情况下修改属性时 实例或首先分离先前拥有的实体条目。'
如何解决?
更新
我的域类:
public class Parent
{
public int Id { get; set; }
public Child Name { get; set; }
public Child ShortName { get; set; }
}
public class Child
{
public List<ChildItem> Items { get; set; }
}
public class ChildItem
{
public string Text { get; set; }
public string Language { get; set; }
}
我的dbcontext:
public class ApplicationContext : DbContext
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Parent>()
.OwnsOne(c => c.Name, d =>
{
d.OwnsMany(c => c.Items, a =>
{
a.HasForeignKey("NameId");
a.Property<int>("Id");
a.HasKey("NameId", "Id");
a.ToTable("ParentNameItems");
})
.ToTable("ParentName");
})
.ToTable("Parent");
modelBuilder.Entity<Parent>()
.OwnsOne(c => c.ShortName, d =>
{
d.OwnsMany(c => c.Items, a =>
{
a.HasForeignKey("NameId");
a.Property<int>("Id");
a.HasKey("NameId", "Id");
a.ToTable("ParentShortNameItems");
})
.ToTable("ParentShortName");
})
.ToTable("Parent");
}
}
用法:
static void Main(string[] args)
{
var context = new ApplicationContext();
var parent = new Parent()
{
Name = new Child()
{
Items = new List<ChildItem>()
{
new ChildItem() { Text = "First value", Language = "en-en"},
new ChildItem() { Text = "Second value", Language = "en-en"}
}
},
ShortName = new Child()
{
Items = new List<ChildItem>()
{
new ChildItem() { Text = "First short value", Language = "en-en"},
new ChildItem() { Text = "Second short value", Language = "en-en"}
}
}
};
context.Set<Parent>().Add(parent);
context.SaveChanges();
}
好吧,首先,您的课程没有意义。如果有的话应该是
public class Parent
{
public int Id { get; set; }
public List<Child> Children { get; set; }
}
父母应该有很多孩子(或者没有可能的是空名单?)。那孩子的名字和身份证呢?也许也许是
之类的东西public class Child
{
public virtual List<ChildItem> Items { get; set; } //why virtual? you planning to inherit?
public string Name {get; set; }
public int Id {get; set; }
public int ParentId {get; set; }
}
看起来好多了,我应该想。数据库应具有匹配表。老实说,EF(实体框架)自动创建将为您完成99%的工作,因此请使用它。
问题已解决。它在线
a.HasKey("NameId", "Id");
在OnModelCreating
方法中。我使用了一个示例,其中写了一个示例以配置自有类型的集合。
从关键定义删除" nameid"字段
a.HasKey("Id");
现在一切正常。