Dal (with Entity Framework) and Model layers into MVC

时间秒杀一切 提交于 2019-12-01 11:36:13

You are right in your idea of not accessing access the Models in your DAL directly from your presentation layer.

To avoid duplicating code when translating your DAL objects into the Models used by your views, you could use something like AutoMapper, which is supposed to do the heavylifting for you in exactly that scenario.

I think it's wrong accessing data layer directly from view to work with these models...

That's right, the appropriate method is using View Model

When you have dozens of distinct values to pass to a view, the same flexibility that allows you to quickly add a new entry, or rename an existing one, becomes your worst enemy .You are left on your own to track item names and values; you get no help from Microsoft IntelliSense and compilers . The only proven way to deal with complexity in software is through appropriate design. So defining an object model for each view helps you track what that view really needs. I suggest you define a view-model class for each view you add to the application.

-- "Programming Microsoft ASP.NET MVC" by Dino Esposito

A ViewModel provides all information that your view requires to make itself. To transfer data from ViewModel and a business entity you can use AutoMapper.

Don't worry about duplication, those are two different concept and should be separated from each other; it makes your application easy to maintain.

I may be mistaking but to me, using generation from EDMX provides you with the DbContext which could be considered as the DAL and entities which could be considered as the Model.

So you might directly manipulate entity instances as your business object. Manipulation of the base through the DbContext should appear in the BLL layer. Additionally, you might implement DTOs where needed.

This, of course, assumes you want to use entity framework code generation. Other options like using POCOs might be more relevant considering your overall architecture.

I use a view model in my local project and the models in the other project. Then put references to the models im gonna use on the page in my view model. Then reference the view model on my page. Let me know if that sounds like something you want to do and I can edit in some code.

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