【发布时间】:2021-12-03 07:54:43
【问题描述】:
我正在尝试使用 EF core 5 将多个关系数据插入 SQL Server DB。 我想插入多个父母和多个孩子。父母和孩子是一对多的关系。我正在尝试使用 context.AddRang(lstparents) 它仅为一个父母插入子实体数据,而其他父母则没有条目。你能帮我解决这个问题吗?
我的模特
Public class Parent
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
Public int64 Id {get; set;}// this is identity column
Public string Name { get; set;}
Public List<Child> child { get; set;}
}
Public class Child
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
Public int64 id { get; set;} // identity column
Public string ChildName { get; set;}
Public int64 ParentId { get; set;}
[Foreign key("ParentId")]
Public Parent parent { get; set;}
}
// Here is insertion logic
Public void main(string[] args)
{
List<Child> lstChild = new List<Child> ()
{
new Child{ ChildName= "Child1Name"},
new Child{ ChildName= "Child2Name"},
new Child{ ChildName= "Child3Name"}
};
List<Parent> lstparents = new List<Parent>()
{
new Parent {Name = "xyz", Child= lstChild },
new Parent {Name = "xyz1", Child= lstChild}
};
Context.AddRangeAsync(lstparents);
Context.SaveChangesAsync();
}
我也尝试了以下选项,但遇到了另一个问题。
选项 1:
Public void main(string[] args)
{
List<Child> lstChild = new List<Child> ()
{
new Child{ ChildName= "Child1Name"},
new Child{ ChildName= "Child2Name"},
new Child{ ChildName= "Child3Name"}
};
List<Parent> lstparents = new List<Parent>()
{
new Parent {Name = "xyz", Child= lstChild },
new Parent {Name = "xyz1", Child= lstChild}
};
foreach(var item in lstparents)
{
Context.Add(item);
foreach(var child in lstChild)
{
Context.Add(child);
}
}
Context.SaveChangesAsync();
}
选项2: 在下面的代码行中,我收到一个错误 “当 IDENTITY_INSERT 设置为 OFF 时,无法为表中的标识列插入显式值”
Public void main(string[] args) {
List<Child> lstChild = new List<Child> ()
{
new Child{ ChildName= "Child1Name"},
new Child{ ChildName= "Child2Name"},
new Child{ ChildName= "Child3Name"}
};
List<Parent> lstparents = new List<Parent>()
{
new Parent {Name = "xyz", Child= lstChild },
new Parent {Name = "xyz1", Child= lstChild}
};
foreach(var item in lstparents)
{
Context.Entry(item).State=EntityState.Added;
foreach(var child in lstChild)
{
Context.Entry(child).State=EntityState.Added;
}
}
Context.SaveChangesAsync();
}
【问题讨论】:
标签: c# .net-core entity-framework-core facebook-c#-sdk