gpt4 book ai didi

entity-framework - 在 mvc 的 Controller 中使用模型类是一种不好的做法吗?

转载 作者:行者123 更新时间:2023-12-04 08:35:28 27 4
gpt4 key购买 nike

在 asp.net mvc 中使用 ORM 或数据库表时,我想与最佳实践进行比较。我的主要问题之一是我应该 实例化 模型类 直接在 Controller 中..不查询数据库,而只是使用模型类来存储值。

例如如果我使用 Entity Framework 作为模型...那么使用实体类对象 是一种不好的做法吗?在 Controller 中 .有时直接使用 Controller 中生成的数据库类而不是创建 ViewModel 甚至 ViewData 更容易。我们有一个数据访问层和一个业务层,其中应用了所有查询和业务逻辑,但虽然更容易我不喜欢在 Controller 中访问模型的想法,但它真的是 不好的做法 ?

最佳答案

是的,这是一种不好的做法,因为“过度发布”的问题。

例如,考虑 UserProfile 的实体模型:

  public class UserProfile
{
public string UserName { get; set; }
public bool IsAdmin { get; set; }
public string EmailAddress { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}

您的用户个人资料页面允许用户编辑他们的名字、姓氏和电子邮件地址。

不道德的用户可以简单地修改表单以发布“IsAdmin”以及其他值。因为您的 Action 需要输入 UserProfile,所以 IsAdmin 值也将被映射,并最终保持不变。

这里是 an excellent writeup about the perils of under and overposting .

不过,我认为将实体模型直接绑定(bind)到您的 [HttpGet] 方法没有任何问题。

关于entity-framework - 在 mvc 的 Controller 中使用模型类是一种不好的做法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3918938/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com