EF代码第一个父 - 子插入与标识列 [英] EF Code First Parent-Child insertions with identity columns

查看:173
本文介绍了EF代码第一个父 - 子插入与标识列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下模型。

class Parent
{
    int ParentId (identity column) { get; set; }
    string ParentName { get; set; }
    virtual ICollection<Child> Children { get; set; }
}

class Child
{
    int ChildId (identity column) { get; set; }
    string ChildName { get; set; }
    int ParentID { get ; set; } //foreign key to Parent(ParentID)
}

如何插入几行给我的父母和孩子单笔交易?基本上我想要获得在父项上生成的身份(比如我在父项中插入一行),并插入带有该值的子行?
如何使用Code First实现?

How do i insert few rows to my parent and child in single transaction? Basically i want to get the identity generated on the parent(say i insert a row in parent) and insert child rows with that value? How this can be achieved using Code First?

推荐答案

你不应该担心 code> Parent 将会被插入 Child 行。这应该是足够的:

You shouldn't worry about what value the Id of Parent will get in order to insert Child rows. This should be enough:

var parent = new Parent
{
    // fill other properties

    Children = new List<Child>()
}

parent.Children.add(new Child { /*fill values */);

dbContext.Parents.Add(parent); // whatever your context is named
dbContext.SaveChanges();

对于记录,ID将在调用 SaveChanges(),所以如果您在插入 Child 实体之前需要该ID,您可以随时调用 SaveChanges ()两次。

For the record, the ID's will be assigned after calling SaveChanges(), so if you really need the ID before inserting a Child entity you can always call SaveChanges() twice.

再次,这不应该是必要的。

Again, this shouldn't be necessary though.

顺便说一下,我建议将Foreign Key属性从 Child Parent 导航属性,因此 Child class将如下所示:

By the way, I would recommend making the Foreign Key property from Child to Parent a navigation property, so the Child class would look like:

class Child
{
    public int ChildId { get; set; } // identity column
    public string ChildName { get; set; }
    public virtual Parent Parent { get ; set; } //foreign key to Parent
}

这样你可以随时访问孩子的父直接而不必自己从数据库中清除它(它将被懒加载)。

That way you can always access the Child's parent directly without having to retrieve it explicitly from the database yourself (it will be lazy loaded).

这篇关于EF代码第一个父 - 子插入与标识列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆