[英]Adding collection of owned objects
我有一个拥有自有类型集合的域模型。 当我尝试在owntyped集合中添加多个对象时? 我得到一个例外:
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
方法中。 我使用了一个示例 ,其中写了abount配置自有类型的集合。
从密钥定义中删除“NameId”字段后
a.HasKey("Id");
现在一切正常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.