我有一个域模型,该模型具有一组拥有的类型。当我尝试在ownertyped集合中添加多个对象时?我有一个例外:
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();
}
答案 0 :(得分:0)
嗯,首先,您的课程没有意义。如果应该的话
public class Parent
{
public int Id { get; set; }
public List<Child> Children { get; set; }
}
父母应该有很多孩子(或者可能没有,可能是空名单?)。那孩子的名字和身份证怎么办,他不是每个孩子都有吗?也可能是ParentId也许是
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%的工作,因此请使用它。
答案 1 :(得分:0)
问题已解决。符合
a.HasKey("NameId", "Id");
在OnModelCreating
方法中。
我使用了example,它是在配置拥有类型的集合的地方写的。
从键定义中删除“ NameId”字段后
a.HasKey("Id");
现在一切正常。