1

我的更新方法将始终更新,因为我必须设置 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

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

4

1 回答 1

6

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

您可以覆盖的SaveChanges()方法DbContext

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);
    }
}
于 2013-05-17T10:56:44.207 回答