views:

190

answers:

2

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.Foo.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.

A: 

I don't know FluentHtml. But regarding the EF:

  1. EF 4.0 lets you have "Foreign key associations", which let you refer to m.Foo.BarId like L2S does.
  2. 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.
Craig Stuntz
Bar is not loaded. This for the creation of a new Foo. With standard Html helpers I want to do Html.DropdownList("Foo.Bar", Model.Bars).
jcm
Then you must either (1) load Bar, or (2) grab the value from BarReference.EntityKey.Values[0]. That said, I never use entities as view models. I create dedicated view models which match the page and write L2E projections to populate them. When you do this, you never have to worry about loading; it's completely automatic and requires no thought on your part.
Craig Stuntz
+1  A: 

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.

Tim Scott
I was really hoping asp.net could do some magic in this regard. I was looking to get away from having to maintain two nearly identical objects just to please the views.
jcm
Monorail (the inspiration for MS MVC) has this: ARDataBind. Having used this I can attest that what at first feels like a pain relief will seriously hurt maintainability, testability and extensibility. Putting persistence concerns into the UI = bad. About the "nearly identical" objects, take a look at AutoMapper. However, if your objects are nearly identical you might have fallen into the anemic doamin anti-pattern.
Tim Scott