Gary McGill
Gary McGill

Reputation: 27516

How to use/persist POCO object relationships in EF?

I have some POCO objects that look something like this:

public class Foo
{
    public int Id { get; set; }
    public string FooProperty { get; set; }
    public int BarId { get; set; }
    public virtual Bar Bar { get; set; }
}
public class Bar
{
    public int Id { get; set; }
    public string BarProperty { get; set; }
    public int FooId { get; set; }
    public virtual Foo Foo { get; set; }
}

Each Foo object has exactly one Bar (and vice-versa).

Now I want to create a new pair of Foo/Bar objects. So I do this (and this is where I suspect I'm going wrong):

var foo = new Foo() { FooProperty = "hello" };

dbContext.Foos.Add(foo);

var bar = new Bar() { BarProperty = "world" };

foo.Bar = bar;

dbContext.SaveChanges();

As you can probably tell, I'm hoping that because I "added" foo, then bar will also be added because it's part of the same object graph, but no: it isn't added - and nor is the FooId of the Bar object updated after the call to SaveChanges (though the Id of the Foo object is updated).

So, my guess is that this behaviour is because I'm dealing with POCOs and not EF proxy objects, and so there's no "plumbing" to make this work. I could fetch the Id from the Foo object and manually stash it in the Bar object (and vice-versa) and make some more calls to SaveChanges, but obviously that's not the right way to go.

So, presumably I need to create EF proxy objects rather than bare POCO objects. What's the best way to do that?

Upvotes: 2

Views: 367

Answers (1)

Mark Oreta
Mark Oreta

Reputation: 10416

If the entities meet the requirements for creating proxy objects, you can make this work by calling the create function from the context itself:

    var foo = dbContext.Foos.Create();
    dbContext.Foos.Add(foo);
    var bar = dbContext.Bars.Create();
    foo.Bar = bar;
    dbContext.SaveChanges();

Upvotes: 3

Related Questions