如何将 EntityFramework、Repository、UnitOfWork 和 Automapper 结合到一个 MVC 应用程序中?
首先,我决定创建一个名为 IDataAccessLayer
的接口,并开始将所有内容放入其中:诸如 GetUsers()
、GetUser(int id)
之类的方法, GetOrderByNumber(int number)
、DeleteOrder(int Id)
等。
一开始效果非常完美。但后来我意识到 DataLayer:IDataLayer 的具体实现正在变得越来越大。我决定将其切成几个部分类文件。但我仍然觉得我做错了什么。
然后我决定为每个逻辑部分创建接口,例如 IUsers
、IOrders
、IItems
等。没有用,因为我通过访问存储库注入到控制器构造函数中的一个依赖属性。因此,每次我需要在控制器中使用不同类型的 dataContext 时,我不能只是添加另一个属性。
然后,经过几个小时阅读有关实体框架的文章后,我终于意识到我必须使用存储库和工作单元模式。我仍然需要以某种方式将 POCO 与 ViewModel 对象分开,尽管它们几乎总是有相似之处。自动映射器有很大帮助。但现在,我不确定如何一起使用所有内容。实体框架、模式、自动映射器和依赖注入框架(如 Ninject)。
我不清楚如何将所有这些混合到一个很棒的架构中。你能给我展示一些很好的例子吗?
First I decided to create one Interface called it IDataAccessLayer
and started putting everything into it: methods like GetUsers()
, GetUser(int id)
, GetOrderByNumber(int number)
, DeleteOrder(int Id)
etc.
That worked just perfect at first. But then I realized that the concrete implementation of DataLayer:IDataLayer
is growing to big. I decided to cut it into several partial class files. Still I was feeling that I'm doing something really wrong.
Then I decided to create interfaces for each logical part like IUsers
, IOrders
, IItems
etc. Didn't work, because I was accessing repository through one dependent property injected into controller's constructor. So I couldn't just add another property everytime I need to use different type of dataContext in my controller.
Then after many hours reading through articles about Entity Framework, I finally realized that I have to use Repository and Unit of work patterns. And still I need to somehow separate POCOs from my ViewModel objects, although almost all the time they'd be sharing similarities. Automapper helps a lot. But now, I'm not sure how to use everything together. Entity Framework, Patterns, Automapper and Dependency injection framework like Ninject.
I don't have clear understanding how to mix that all into one awesome architecture. Can you please show me some nice examples.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以查看我几个月前编写的此示例 (MVCArch)。
它利用了:
希望这有帮助。
You might take a look at this sample (MVCArch) I've written some months ago.
It takes advantages of :
Hope this helps.
首先,这是一篇关于使用存储库和 UnitOfWork 原则的 n 层架构的整体文章:链接。我有一些使用 EF 和上述模式的经验,我发现这篇文章很有帮助。
请查看此处以及此处 查看有关这些原则的 MSDN 文章。
问候。
First here is an overall article about n-tier architecture using the Repository and UnitOfWork principles: link. I have some experience working with EF and the afore mentioned patterns and I found this article of great help.
Take a look here as well as here for the MSDN articles on those principles.
Regards.
您是否经历过 这些教程。
Did you go through these tutorials.