ASP.Net MVC如何将视图模型与数据库模型分开? [英] ASP.Net MVC How to separate view models from DB models?

查看:218
本文介绍了ASP.Net MVC如何将视图模型与数据库模型分开?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定如何将视图模型与数据库模型分离.

I can't quite decide how to go about separating my view models from my DB models.

我正在使用ActiveRecord模式进行数据库访问.意思是我为数据库中的每个User行都获得了一个User类实例.

I'm using an ActiveRecord pattern for my DB access. Meaning I get a User class instance for each User row in the database.

在WebForms中,我习惯将它们用作模型对象,直接在ActiveRecords上实现大多数业务逻辑.

In WebForms I'm used to use these as my model objects, implementing most of the business logic directly on my ActiveRecords.

我意识到这并不是完全三层设计,我真的很想对其进行改进,尤其是在关注分离问题的MVC中.

I realize this isn't exactly 3-tiered design, and I'd really like to improve upon it, especially in MVC, where separation of concerns is empathized.

所以我认为Controller不应该访问我的数据库模型,但是我该如何去从数据库存储/加载数据呢?

So I'd think the Controller shouldn't have access to my DB models, but how do I then go about storing/loading data from the DB ?

我也不应该在视图模型中放置大量的业务逻辑,所以我想我还是缺少了一个难题的中心部分.

It's not my impression you should place a huge amount of business logic in your view models either, so somehow I think I'm missing a central piece of the puzzle.

我正在寻找的是一些我认为是最佳实践的建议:-)

What I'm looking for is some best-practice advice I guess :-)

我希望所有这些都说得通,否则请问.

I hope all this made sense, otherwise please ask.

推荐答案

我强烈建议为每个视图创建一个视图模型,并使用 AutoMapper 可以将活动记录中的属性映射到视图模型.我不认为您的控制器可以访问您的数据库模型存在问题;控制器应该负责将它们转换为视图模型.

I strongly suggest creating one view model per view and using AutoMapper to map properties from your active records to your view models. I don't believe that there's a problem with your controller having access to your DB models; the controller should be responsible for translating them into view models.

关于将视图模型(实际上是数据模型)转换回活动记录,在简单情况下,您也可以使用AutoMapper,其余部分则可以使用自定义代码.

As for translating view models (really post data models) back into active records, you can use AutoMapper for this as well in simple cases and custom code for the rest.

这篇关于ASP.Net MVC如何将视图模型与数据库模型分开?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆