实体框架代码优先 - 保存实体时设置属性的最佳方法是什么

发布于 2025-01-01 04:31:23 字数 438 浏览 3 评论 0原文

我正在使用 Entity Framework 4.1 并使用代码优先方法。

这是我的类

public class Dummy {
    public string Name { get; set; }
    public DateTime lastModifiyed { get; set; }
}

我想做的是,每次保存虚拟对象时,lastModifiyed 属性都应设置为当前时间。

即使我使用所需的属性,此代码仍然有效。

var d = new Dummy();
d.lastModifiyed = DateTime.MinValue

做这类事情的最佳实践是什么?我读过,重写从 DbContext 继承的类中的 SaveChanges 并检查例如接口是一个很好的方法。或者我该怎么办?

I'm using Entity Framework 4.1 and using the code first approch.

This is my class

public class Dummy {
    public string Name { get; set; }
    public DateTime lastModifiyed { get; set; }
}

What I'm trying to do is that everytime the Dummy object is saved the lastModifiyed property should be set to the current time.

Even if I'm using attribute like requried this code will still be valid.

var d = new Dummy();
d.lastModifiyed = DateTime.MinValue

What is the best practies to do this kind of stuff. I have read that override the SaveChanges in the class that Inherits from DbContext and check for example a interface is a good way to go. Or how should I do?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

能怎样 2025-01-08 04:31:23

重写 SaveChanges 方法,并在调用 base.SaveChanges 之前枚举更改跟踪器中的更改。 IE:

foreach (var item in (this as IObjectContextAdapter).ObjectContext.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified | EntityState.Deleted)
    .Where(entry => entry.Entity is ITracksLastModified)
    .Select(entry => entry.Entity as ITracksLastModified))
{
    item.LastModified = DateTime.UtcNow;
}

Override the SaveChanges method and before calling base.SaveChanges enumerate changes from change tracker. I.e:

foreach (var item in (this as IObjectContextAdapter).ObjectContext.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified | EntityState.Deleted)
    .Where(entry => entry.Entity is ITracksLastModified)
    .Select(entry => entry.Entity as ITracksLastModified))
{
    item.LastModified = DateTime.UtcNow;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文