shadeglare
shadeglare

Reputation: 7536

Entity Framework: saving related entities

I've got two entities that have a 1-many relation but also a 1-1 relation.

Here's a simple illustration:

class Parent
{
    public Int32 Id { get; set; }
    public List<Child> Children { get; set; }
    public Int32 LastChildId { get; set; }
    public Child LastChild { get; set; }
}

class Child
{
    public Int32 Id { get; set; }
    public Int32 ParentId { get; set; }
}

And an instantiation:

var c1 = new Child() { };
var c2 = new Child() { };

var p = new Parent()
{
    Children = new List<Child> { c1, c2 },
    LastChild = c2
};

Will Entity Framework keep the last child id after the Parent object p will be inserted into the db via the datacontext?

Upvotes: 0

Views: 1350

Answers (1)

Brian Mains
Brian Mains

Reputation: 50728

If you did:

context.Parents.Add(p);
context.SaveChanges();

In your above code, that parent p will have the ID of c2 as the value of LastChildID. The parent will also have relationships to both children through the cross-reference table. Both of those children will have a reference to p through it's Parent entity property.

Upvotes: 1

Related Questions