我的更新方法将始终更新,因为我必须设置 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
你能告诉我如何防止每次都执行查询吗?