How to overcome the Model → ViewModel impedance mismatch?
I'm baffled.
I have my linq-to-sql model which is a mirror of a database table
(Id, CustomerId, RegionId,...N),
nothing interesting, all foreign keys. Now I need to view this data in my asp.net view. I create a ViewModel
(开发者_Go百科Id, CustomerId, Customer, RegionId, Region, CustomersSelectList, RegionsSelectList).
Clearly, the viewmodel is a superset of a linq-to-sql model.
Now how do I transform one to another? I'm using automapper but puzzled as to how to find good patterns for getting missing data.
I see possible solutions:
Create 3rd class, which will be a l2s model + joined values and fill this class by joining and projecting. Then automap this class to my viewmodel.
Return anonymous classes via projection and map them to viewmodels via automapper (not very clean).
Create db views for querying (views are all required tables joined together).
Please help me with that, because earlier I've been using my L2S classes directly in views (on simple projects), now I have more complex views and need to do something to tackle complexity.
Also, whose responsibility is to do this transformation? Where should it happen?
Thank you.
UPDATE: let me clarify a bit. I need to be able to get full flat representation of my business entity. In db it is stored in multiple tables, in L2S it is many classes (mirror db tables), in my ViewModel it should be 'accumulated' from many db tables.
Should I perform sql joins via linq and fill the ViewModel directly?
Should I create a business entity (not linq one), with all the fields, and fill it with linq to sql and then automap it to ViewModel?
Should I stop using L2S class as a business entity, create a new business entity class from scratch and treat L2S as a dumb ORM instead?
I'm not familiar enough with automapper to know if this will actually work, but I would think that you could do it in two steps. First, let automapper map all of the properties that are mirrors of each other. Next, either have logic inside the other properties that can get the correct values or set them from the object that initiated the mapping.
精彩评论