Domanda

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.

È stato utile?

Soluzione

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top