c# – 实体框架6 SaveChanges()覆盖不一致地检测更改

c# – 实体框架6 SaveChanges()覆盖不一致地检测更改,第1张

概述我已经扩展了一个类,以便在记录发生重大更改时将最后修改的时间戳添加到记录中.这是使用类似于 this的代码完成的. 这是我的问题. SaveChanges()正在为两个更改触发,但第二个没有进入循环:没有检测到对象需要更改. 但是,EF会通过base.SaveChanges()调用更新记录. 这是MasterTable的扩展: namespace AuditTestEF{ public 我已经扩展了一个类,以便在记录发生重大更改时将最后修改的时间戳添加到记录中.这是使用类似于 this的代码完成的.

这是我的问题. SaveChanges()正在为两个更改触发,但第二个没有进入循环:没有检测到对象需要更改.

但是,EF会通过base.SaveChanges()调用更新记录.

这是Mastertable的扩展:

namespace AuditTestEF{    public interface IHasAuditing    {        DateTime LastModifIEdOn { get; set; }        int LastModifIEdBy { get; set; }    }    public partial class Mastertable : IHasAuditing    {    }    public class AuditTestEntitIEsWithAuditing : AuditTestEntitIEs    {        public int TestingUserIs = 1;        public overrIDe int SaveChanges()        {            foreach (ObjectStateEntry entry in (this as IObjectContextAdapter)                .ObjectContext                .ObjectStateManager                .GetobjectStateEntrIEs(EntityState.Added | EntityState.ModifIEd))            {                // This loop is entered the first time,but not the second                if (entry.IsRelationship) continue;                var lastModifIEd = entry.Entity as IHasAuditing;                if (lastModifIEd == null) continue;                lastModifIEd.LastModifIEdOn = DateTime.UtcNow;                lastModifIEd.LastModifIEdBy = TestingUserIs;            }            return base.SaveChanges();        }    }}

这是测试工具:

[TestMethod]public voID TestMethod1(){    Mastertable mtOriginal;    using (var audit = new AuditTestEntitIEsWithAuditing())    {        var message = "Hello";        audit.TestingUserIs = 1;        mtOriginal = new Mastertable {TextFIEld = message};        audit.Mastertable.Add(mtOriginal);        audit.SaveChanges();        // This test passes,TestingUser is set in the overrIDe        Assert.IsTrue(mtOriginal.LastModifIEdBy == audit.TestingUserIs);        }    using (var audit = new AuditTestEntitIEsWithAuditing())    {        var mt = audit.Mastertable.Find(mtOriginal.MastertableID);        mt.TextFIEld = "Goodbye";        audit.TestingUserIs = 4;        audit.SaveChanges();        // This test fails,the record is written with "Goodbye" but        // GetobjectStateEntrIEs(EntityState.Added | EntityState.ModifIEd) has no entrIEs.        Assert.IsTrue(mt.LastModifIEdBy == audit.TestingUserIs);                }}

没有其他代码.实体跟踪或任何事情都没有奇怪的关闭/开启.所见即所得.

我错过了什么?如何通过检查修改错过了明确修改的对象?

解决方法 安德……当然,在与鸭子交谈之后回答了我自己的问题.

public overrIDe int SaveChanges()    {        ChangeTracker.DetectChanges();

这解决了一切.感谢您的关注,我希望这有助于其他人.

总结

以上是内存溢出为你收集整理的c# – 实体框架6 SaveChanges()覆盖不一致地检测更改全部内容,希望文章能够帮你解决c# – 实体框架6 SaveChanges()覆盖不一致地检测更改所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1226760.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存