【问题标题】:Generic check if something has changed with entity framework and repository pattern通用检查实体框架和存储库模式是否发生了变化
【发布时间】:2013-05-17 09:34:02
【问题描述】:

我的更新方法将始终更新,因为我必须设置 LastModified 日期。我想知道是否有一种方法可以动态检查某些值是否已更改。

我的状态对象如下所示:

public partial class Action : IEntity
{
    public long Id { get; set; }
    public string Code { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public System.DateTime Created { get; set; }
    public System.DateTime LastModified { get; set; }
    public Nullable<System.DateTime> Deleted { get; set; }
}

我使用的界面如下所示:

public interface IEntity
{
    long Id { get; set; }        
    DateTime Created { get; set; }
    DateTime LastModified { get; set; }
    DateTime? Deleted { get; set; }       
}

我的更新方法如下(稍后保存更改):

    public virtual void Update(T entity)
    {
        DbEntityEntry dbEntityEntry = DbContext.Entry(entity);
        var attachedEntity = DbSet.Find(entity.Id);

        if (attachedEntity != null)
        {
            var attachedEntry = DbContext.Entry(attachedEntity);

            entity.Created = attachedEntity.Created;
            entity.LastModified = DateTime.Now;

            attachedEntry.CurrentValues.SetValues(entity);
        }
        else
        {
            dbEntityEntry.State = EntityState.Modified;
            entity.LastModified = DateTime.Now;
        }
    }

因此,它实际上会对使用IEntity 接口作为 T 传递的每个对象执行通用更新。但是,由于LastModified 值已更改,因此每次调用此方法时都会执行更新。导致许多更新查询如下:

exec sp_executesql N'update [dbo].[BiztalkEntity]
set [LastModified] = @0
where ([Id] = @1)
',N'@0 datetime2(7),@1 bigint',@0='2013-05-17 11:22:52.4183349',@1=10007

您能告诉我如何防止每次都执行查询吗?

【问题讨论】:

  • @bzlm 感谢您的快速响应,但这确实有效。我只是想知道如何检查更改,然后不设置上次修改的值,因此不会更新。

标签: c# entity-framework generics repository


【解决方案1】:

我建议你延迟LastModified 的设置,让Entity Framework 为你提供在更改发送到数据库之前已更改的所有实体。

你可以覆盖DbContextSaveChanges()方法

public class MyContext : DbContext
{
    public override int SaveChanges()
    {
        //you may need this line depending on your exact configuration
        //ChangeTracker.DetectChanges();
        foreach (DbEntityEntry o in GetChangedEntries())
        {
            IEntity entity = o.Entity as IEntity;
            entity.LastModified = DateTime.Now;
        }
        return base.SaveChanges();
    }

    private IEnumerable<DbEntityEntry> GetChangedEntries()
    {
        return new List<DbEntityEntry>(
            from e in ChangeTracker.Entries()
            where e.State != System.Data.EntityState.Unchanged
            select e);
    }
}

【讨论】:

  • 听起来不错,但我认为我无法从 DbEntityEntry 中获取 IEntity,或者可以吗?立即尝试
  • @NickN。 DbEntityEntry.Entity msdn.microsoft.com/en-us/library/…
  • @NickN。它从来没有给我任何问题。
  • ChangeTracker 来自哪里?在什么命名空间中?
  • 它不影响我的查询,你认为是因为它仍然检测到变化吗?现在 LastModified 属性仍然为每个保存的对象设置,这是一件好事。但我只是不想让一些人一开始就得救。因为它们并没有真正改变
猜你喜欢
  • 2010-12-11
  • 1970-01-01
  • 2018-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多