Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
832 views
in Technique[技术] by (71.8m points)

entity framework - EF Code First Parent-Child insertions with identity columns

i have the following model.

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)
}

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();

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.

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...