kro*_*761 5 entity-framework-core
使用 Entity Framework Core 将数据插入多个表(其中一个或多个新记录包含第一个表的外键)的最佳方法是什么?
鉴于这些实体:
public class ParentEntity
{
public int Id {get; set;}
public string Name {get; set;}
}
public class ChildEntity
{
public int Id {get; set;}
public int ParentId {get; set;}
public string Name {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
我知道我可以使用这种方法插入数据:
var parentEntity = new ParentEntity {Name = "Mom"};
var childEntity = new ChildEntity {Name = "Junior"};
await db.Parents.AddAsync(parentEntity);
childEntity.ParentId = parentEntity.Id;
await db.Children.AddAsync(childEntity);
await _context.SaveChangesAsync();
Run Code Online (Sandbox Code Playgroud)
但我可以看到这不会很好地扩展。我现在正在学习 EF Core,我找不到更好的方法来处理这个问题。
Jan*_* Go 10
如果你真的需要只使用外键,那么你应该这样做......就像进行手动 SQL 查询一样。
但 EF 支持导航属性的概念。所以你可以像这样定义你的类:
public class ParentEntity
{
public int Id {get; set;}
public ICollection<ChildEntity> Children { get; } = new List<ChildEntity>();
}
public class ChildEntity
{
public int Id {get; set;}
public int ParentId {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
然后像这样使用它
var parentEntity = new ParentEntity();
parentEntity.Children.Add(new ChildEntity());
context.Parents.Add(parentEntity); // parent and its children gets added
context.SaveChanges();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12800 次 |
| 最近记录: |