我目前正在寻找正确检查我的授权框架是否已添加,修改或删除的方法。以下是我的编码:
int state = 0;
var added = this.ChangeTracker.Entries().Where(e => e.State == EntityState.Added).ToList();
var modified = this.ChangeTracker.Entries().Where(e => e.State == EntityState.Modified).ToList();
var deleted = this.ChangeTracker.Entries().Where(e => e.State == EntityState.Deleted).ToList();
if (added.Count > 0)
state = 1;
if (modified.Count > 0)
state = 2;
if (deleted.Count > 0)
state = 3;
目前正在运作。我只想知道是否还有其他正确的方法。
答案 0 :(得分:0)
改善表现
Any
而不是创建包含所有实体的列表。state
值
代码:
int state = 0;
if (this.ChangeTracker.Entries().Any(e => e.State == EntityState.Deleted))
{
state = 3;
}
else if (this.ChangeTracker.Entries().Any(e => e.State == EntityState.Modified))
{
state = 2;
}
else if (this.ChangeTracker.Entries().Any(e => e.State == EntityState.Added))
{
state = 1;
}
答案 1 :(得分:0)
如果您使用的是实体框架6,则可以override SaveChanges()
public override int SaveChanges()
{
var addedEntites= ChangeTracker.Entries<IfYouWantSpecifyAnyType>()
.Where(p => p.State == EntityState.Added)
.Select(p => p.Entity);
var modified= ChangeTracker.Entries<IfYouWantSpecifyAnyType>()
.Where(p => p.State == EntityState.Modified)
.Select(p => p.Entity);
var now = DateTime.UtcNow;
foreach (var added in addedEntites)
{
added.CreatedAt = now;
added.LastModifiedAt = now;
}
foreach (var modified in modified)
{
modified.LastModifiedAt = now;
}
return base.SaveChanges();
}
@Matthias Burger建议它会对性能产生影响,我也建议使用触发器或留在数据库端的东西。