ASP.Net MVC 如何将视图模型与数据库模型分离?
我无法完全决定如何将视图模型与数据库模型分开。
我正在使用 ActiveRecord 模式进行数据库访问。这意味着我为数据库中的每个用户行获取一个用户类实例。
在 WebForms 中,我习惯使用它们作为我的模型对象,直接在我的 ActiveRecords 上实现大部分业务逻辑。
我意识到这并不完全是 3 层设计,我真的很想对其进行改进,尤其是在 MVC 中,其中关注点分离得到了重视。
所以我认为控制器不应该访问我的数据库模型,但是我该如何从数据库存储/加载数据呢?
我的印象也不应该在视图模型中放置大量的业务逻辑,所以不知怎的,我认为我错过了这个难题的核心部分。
我想我正在寻找一些最佳实践建议:-)
我希望这一切都是有意义的,否则请询问。
I can't quite decide how to go about separating my view models from my DB models.
I'm using an ActiveRecord pattern for my DB access. Meaning I get a User class instance for each User row in the database.
In WebForms I'm used to use these as my model objects, implementing most of the business logic directly on my ActiveRecords.
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.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我强烈建议为每个视图创建一个视图模型,并使用 AutoMapper 将属性从活动记录映射到视图模型。我不认为您的控制器访问数据库模型有问题;控制器应该负责将它们转换为视图模型。
至于将视图模型(真正发布数据模型)转换回活动记录,您也可以在简单的情况下使用 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.
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.