开发者

Saving Dropdown list selection with Entity Framework in ASP.NET MVC solution

I'm looking for advice on a decent pattern for dropdown list selection and persistence of the selection with POCO EF please.

I have a list of IEnumerable<Country> in my view model where Country is a POCO loaded via EF. There is an Address property on the view model that takes the current or user selected value on it's Country property. Within the view I display these via a Html.DropdownListFor() thus:

Html.DropDownListFor(model => model.Address.Country.Id, new SelectList(Model.Countries,"Id","Name",model.Address.Country.Id)

So far so good and it all works on postback with the default ModelBinder providing me with a view model with the Address.Country populated. However Address.Country is of course only populated with the Id field with default model binding.

Trying to send the Address update back to the DB through EF blows up as this is seen as a ne开发者_Go百科w object which doesn't have it's full object graph loaded, only the Id set.

Now I can fix this by loading the full Country object from the db into the Address.Country property on postback before saving based on the selected Id. But this seems like a lot of hard work for anything beyond a simple object graph.

The most "elegant" solution I could think of would be a custom model binder for Country but then that would require the Model Binder to know about the repository for retrieving the full EF object which doesn't seem right to me. I'd also have to repeat this for all other Entities used in Dropdown lists.

Hope this makes sense and any feedback on how others are doing this would be appreciated.


If you set Address.Country to an object, EF expects it to be a full object that's part of the current context, but EF does recognize foreign keys: If your Address object has both a CountryID property and a Country property, it should accept Address.CountryID being set as long as Address.Country itself is null.


In your Address class declare country as virtual

public class Address
{
  public virtual Country Country;
}

try this and let me know if it works, Virtual supports lazyloading and you don't have to query explicitly

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜