1

Here's the scenario.
Example models:

public class Foo {
    public int Id {get;set;}
    public virtual Bar Bar {get;set;}
}

public class Bar {
    public int Id {get;set;}
    public string Name {get;set;}
}

In my view, to create the Foo object, it has a DropDownList of Bar objects that already exists.
This DropDownList has its values with the Bar's Ids.
Something like this:

@Html.DropDownListFor(n => n.Bar.Id, new SelectList(ViewBag.Bars, "Id", "Name"))

When the form is submited, MVC binds the values corretly to the Foo object, and also creates a new Bar object with only the Id setted.

When I try to save the object, EF returns an exception. It tries to create a Bar object, which will fail, because the Bar object has only the Id set.
I thought EF was smart enought to get the Id set in the Bar and fetch it.

So my question is: Is there a way to set the relationship through a navigation property without having to fetch it before?

My models does not have a exposed foreign key to its navigation properties, and I'm searching for a solution that does not need it.

1 Answers1

0

You need Foo.BarID property for EF to figure out how to persist your tree. There is no other way.

Maxim Balaganskiy
  • 1,524
  • 13
  • 25
  • Thanks for the reply. I'm almost givin' up, but I still think there's another way to set it without a foreign key exposed, because I saw someone here posting it as an answer, but I just can't find it any more :(. – Vinícius Oliveira Mar 04 '14 at 01:17
  • was it this answer http://stackoverflow.com/questions/5691780/navigation-property-without-declaring-foreign-key – Maxim Balaganskiy Mar 04 '14 at 01:20
  • unfortunately not. In the answer, they explicit said that EF could recognize and auto fetch a navigation property if only its Id is setted. So I tried, and got the error. Perhaps I'm wrong, and its really not possible. Think I'll wait a little more... – Vinícius Oliveira Mar 04 '14 at 01:27