在插入数据库之前在哪里设置实体的 CreatedOn 属性
假设我有一个实体,如下所示:
Restaurant
- Id : int
- Name : string
- CreatedOn : datetime (当它添加到数据库时)
,并且我有一个 RestaurantService 和 RestaurantRepository 类。这两个类都有一个 AddRestaurant 方法。 RestaurantService 类对实体执行一些工作,然后将实体传递到存储库以进行持久化。
这两个类中的哪一个应该负责设置 CreatedOn 属性?
存储库应该负责设置 CreatedOn 属性,还是应该将其作为服务类职责的一部分?
Say I have an entity as follows:
Restaurant
- Id : int
- Name : string
- CreatedOn : datetime (when it was added to the DB)
and I have a RestaurantService and RestaurantRepository classes. Both of these classes have an AddRestaurant method. The RestaurantService class does some work on the entities and then passes the entities to the repository for persistance.
Which of the two classes should be in charge of setting the CreatedOn property?
Should the repository be in charge of setting the CreatedOn property or should that be part of the Service class responsibility?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我个人会将其尽可能靠近数据库 - 包括实际上在数据库中,如果这满足您的需求。否则,无论在最接近实际持久化点的地方,因为这就是
CreatedOn
最初的含义。I would personally put it as close to the database as possible - including actually in the database, if that meets your needs. Otherwise, though, wherever is closest to the point where it is actually persisted, because that's what is meant by
CreatedOn
in the first place.由于记录最终由数据库本身保存,因此每当添加实体时指示数据库生成当前日期是有意义的。
您可以在实体中进行配置,而无需接触数据库。例如,在 Entity Framework 7(最新的 RC1)中,
假设我有一个实体
,然后在我的上下文类中,在模型创建时,我实例化映射(我可以在那里进行映射,但我喜欢将其分开),
然后映射。 (记住使用模型扩展所在的命名空间)。在下面的说明中,我告诉实体该值是在添加记录(实体)时生成的,并且应用程序不需要手动设置日期时间。相反,我告诉它在添加实体时执行 SQL Server 函数
GETUTCDATE()
,这样我就不再需要担心这个问题了。关于您对数据库时区的担忧,好的做法是始终在数据库中将日期保存为 UTC(与位置无关),并根据用户位置转换日期,以便用户始终看到本地日期。这就是为什么数据库的指令是
GETUTCDATE()
而不是GETDATE()
As the record is persisted eventually by the Database itself, it makes sense to instruct the database to generate the current date whenever an entity is added.
You can configure that in Entity without touching the database. For example in Entity Framework 7 (the latest as per RC1)
Say I have an entity
then in my context class, on model creating, I instantiate the mapping (I could do the mapping there, but I like to keep it separated)
and then the mapping. (Remember to use the namespace where the Model extensions are). In the instruction below I tell Entity that this value is generated when adding records (entities) and that the application does not need to manually set the datetime. Instead I tell it to execute the SQL Server function
GETUTCDATE()
when adding an entity so I don't need to worry about that anymore.About your concern about database time zone, the good practice is to ALWAYS save dates as UTC in database (location agnostic) and transform the date as per the user location so the user always sees local date. That's why the instruction for the database is
GETUTCDATE()
rather thanGETDATE()