EF Code First Parent-Child insertions with identity columns

后端 未结 2 1507
离开以前
离开以前 2020-12-13 10:37

i have the following model.

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

        
2条回答
  •  攒了一身酷
    2020-12-13 11:02

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

提交回复
热议问题