将Linq2Sql对象传递给View有什么问题? [英] What's wrong with passing Linq2Sql objects to Views?

查看:47
本文介绍了将Linq2Sql对象传递给View有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

上一个问题中,@ Darin Dimitrov

In a previous question, @Darin Dimitrov answered:

在您的情况下,最糟糕的是 您正在使用您的Linq2Sql模型 在您的意见之内,这是其中之一 我看到的最糟糕的反模式 在ASP.NET MVC应用程序中执行.你 绝对应该使用视图 楷模.那就是应该的观点 从控制器传递过来的 控制器应该从中得到什么 视图.

In your case the worst thing is that you are using your Linq2Sql models inside your views and that's one of the worst anti-patterns I see people doing in ASP.NET MVC applications. You absolutely should be using view models. That's what views should be passed from controllers and that's what controllers should get from views.

为什么将Linq2Sql对象作为模型传递这么糟糕?

Why is it so bad to pass Linq2Sql objects as Models?

推荐答案

将Linq2Sql对象作为模型传递给您的视图和控制器很不好,这有很多原因,要覆盖其中的所有对象将相对困难.一个答案.所以,这是我的前3名:

There are a lot of reasons why it's bad to pass Linq2Sql objects as models to your views and controllers, and it would be relatively difficult to cover all of them in a single answer. So, here are my top 3:

关注点分离-Linq2Sql对象中嵌入了DAL逻辑,这违反了SoC.同样,您可能希望验证从视图传递的数据,这应该在模型中完成(而不是控制器!).但是,如果将此逻辑添加到L2S模型中,那么还会违反SoC(更不用说重新生成L2S模型会清除您的验证的事实)

Separation of Concerns - Linq2Sql objects have DAL logic embedded in them, which is a violation of SoC. Also, you will likely want to validate data passed from your views, which should be done in the Model (NOT the controller!). However, if you add this logic to your L2S models then you also violate SoC (not to mention the fact that your validations will be wiped out if you regenerate your L2S models)

封装-您的L2S类具有很多成员,您的视图和控制器可能不需要访问这些成员.适当的模型将封装这些成员,以使其无法访问.

Encapsulation - Your L2S classes have a lot of members that your view(s) and controller(s) likely do not need access to. A proper model would encapsulate these members to keep them inaccessible.

可维护性和可重用性-在某些时候,您可能会决定要更改后备存储.如果将L2S类用作模型,则最终需要触摸大量代码进行更改,而如果滚动自己的模型,则只需要担心更改模型,而无需担心其他任何事情.另外,不弄乱您的L2S模型(请参见上面的SoC)意味着它们可以在项目中重复使用.

Maintainability and Reusability - At some point you may decide you want to change your backing store. If you use your L2S classes as models then you'll end up touching a LOT of code to make that change, whereas if you roll your own models then you'll only have to worry about changing your models and nothing else. Also, not messing with your L2S models (see SoC above) means that they're reusable across projects.

这篇关于将Linq2Sql对象传递给View有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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