I’m using Entity Framework 4.1 (database first, e.g “old school”), and i’m using POCOs in an ASP.NET MVC 3 web app.
I’ve got a 1 – 0..1 relationship between Foo and Bar, backed by a nullable int on the Foo table.
My POCO’s look like this:
public class Foo
{
public Bar Bar { get; set;
}
public class Bar
{
public int BarId { get;set; }
}
Now, i have a Foo which already exists in the system, but BarId is null.
Now i’m trying to associate that Foo with an existing Bar.
This is the code i’ve got:
var existingBar = _repo.GetBar(2);
var existingFoo = _repo.GetFoo(1);
existingFoo.Bar = existingBar;
But behind the scenes, EF is adding a new Bar. Why?
I also tried this:
existingFoo.Bar = new Bar { BarId = 2 };
E.g the “stub technique”, but results in EF complaining about empty columns (because again, it’s trying to create a “new” Bar).
I’m sure i’ve done this before – i just hope the solution i ended up going with wasn’t “use a SP”.
As i mentioned – i’m using POCO’s, so i don’t have direct access to the DbContext or ObjectContext from my controller.
Any advice?
I suspect that’s because
The above was quoted from Ladislav Mrnkva’s blog post. Try to define the
BarIdproperty in yourFooclass and see if it causes the context to work properly.