Binding EF4 with Caliburn.Micro: Should I expose my Entity as a property of the ViewModel?

孤者浪人 提交于 2019-12-04 07:38:09

With Caliburn.Micro I'd like to know the pros and cons of exposing an EF4 Entity as a property of the ViewModel (a technique discussed here and here).

I'm not sure of the pros/cons but I can tell you both methods are used. For example take a simple Login Screen, generally I put the UserName a property on the ViewModel but in cases where the form is more complex the ViewModel can aggregate other ViewModels(display models) to accomplish the same thing. CM doesn't effect the pros/cons much as its more a question of With MVVM, what are the pros/cons. CM is going to help you in binding to both.

  • If you have a property on the ViewModel called CustomerName, simply name a TextBox x:name="CustomerName".
  • If you have a property on the ViewModel that is a instance of a class called Customer, name the TextBox x:name="Customer_Name" and again, CM will handle the bindings.

So from your xaml above:

 <TextBox x:Name="LastName" Text="{Binding LastName}" />

you don't need to set the DataContext on the StackPanel. Instead:

<TextBox x:Name="OneCustomer_LastName"/>

One thing that can make binding to DataForms and DataGrids easier is following a method where you create display models for the way the data is represented on the screen.

This is my opinion but I personally will never bind directly to an EF/Linq entity. Instead I'll create a display model to represent that entity and how I want it displayed and use AutoMapper to do the mappings. In a lot of cases its a one to one mapping. This might seem like a waste of time but it has advantages especially with more complex data model layouts, display models allow you to flatten the data for display purposes and attribute up properties for validation without sticking them on the data model entity. For more on that check out the chapter on it in ASP.NET MVC in Action book.

Since there are other advantages of exposing entities (for example, validation through attributes), I personally do expose them directly.

But I guess the proper answer would be "it depends" as there are always some drawbacks too (mainly architectural).

BTW: you can call the textbox "OneCustomer_LastName" and C.M's convention binding will work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!