What I'm looking to do is set a Foreign Key object in an EF entity via FluentHtml. I have an entity of Foo with a reference to the object Bar via Foo.Bar. What I am trying to do is set the value of Bar in my view form. My models contains a collection of all Bars via Model.Bars. In my view I'm simply using <%= this.Select(m => m.F开发者_高级运维oo.Bar).Options(Model.Bars) %>
but the model state claims it is not valid. The dropdown is properly filled with Bar ids and it all looks valid. Is there some special magic I need for setting EF entity reference properties in my forms?
I just moved over from Linq2SQL where I was simply using Select(m => m.Foo.BarId) as you could have the key reference mapped as well as the object. However, Entity Framework does not allow this.
You are encountering one of the many complications that arise from using business objects as your view models. I might suggest that in the long run, it's much less trouble if you transform business objects to lightweight view models for rendering and binding. Let your service layer (or controller, if you must) figure out how to set Foo.Bar based on EditFoo.BarId.
I don't know FluentHtml. But regarding the EF:
- EF 4.0 lets you have "Foreign key associations", which let you refer to m.Foo.BarId like L2S does.
- In EF 1, or with "independent associations" in EF 4, you need to do m.Foo.Bar.Id (note extra dot), provided that Bar is loaded.
精彩评论