在 ASP.NET MVC 中初始化对象的正确位置
我是 MVC 编程方式的新手,所以请耐心解答我的基本问题!
我有一个带有默认构造函数的 Status 类(在 ASP.NET MVC 应用程序中)。
public Status()
{
this.DatePosted = DateTime.Now;
}
我注意到 Fluent NHibernate 每次从数据库获取现有 Status 对象的列表时都会调用这个构造函数。因此,构造函数似乎不是初始化日期的正确位置。
我应该把这个初始化移到哪里?将其移至控制器(状态控制器的添加操作)似乎也违反了控制器不应做出任何业务决策的原则。那么我应该将其移至 Status DAO 吗? (在我使用的传统 ASP.NET Web 窗体应用程序中,DAO 只是接受业务对象并将其保存到数据库中,不包含任何逻辑)
我想知道完成此操作的正确方法。我在这里还缺少另一层应该进行初始化的地方吗?
I am new to the MVC way of programming so please bear with my basic question !
I have a Status class with a default constructor (in an ASP.NET MVC application).
public Status()
{
this.DatePosted = DateTime.Now;
}
I noticed Fluent NHibernate calls this constructor each time it fetched a list of existing Status objects from the database. Hence, the constructor does not seem like the right place to initialize the date.
Where should I move this initialization ? Moving it to the Controller (Add action of Status controller) also seems to violate the principle that the Controller should not make any business decisions. Should I move it to the Status DAO then ? (In traditional ASP.NET Web Form applications I worked with, a DAO simply accepted a business object and saved it to the database and did not contain any logic)
I would like to know the right way to accomplish this. Is there another layer I am missing here where this initialization should take place?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
但这正是应该发生的事情。为什么 ORM 不调用对象的默认构造函数?我认为世界上每一手的 DAL 和 ORM 都会触发 DatePosted 重置,因为这就是构造函数的工作方式。
您的 DatePosted 属性可能应该通过 ModelBinding 设置或在控制器中手动设置,而不是构造函数的一部分。
This is exactly what is supposed to be happening. Why wouldn't an ORM call the default constructor for an object? I think every hand rolled DAL and ORM in the world would trigger DatePosted to be reset because thats just how constructors work.
Your DatePosted property should probably set via ModelBinding or manually in the controller and not be part of a constructor.