我使用EF Code First但我的模型没有关系(PKs - FKs)。所以我试图找到一种方法来解决它,通过使用EF6反射,以避免具有关系的条目删除(相同的属性名称)。
如果为false,则保持实体状态被删除并保存我的上下文更改;
public override int SaveChanges()
{
foreach (var myEntity in ChangeTracker.Entries<IAuditable>())
{
if (myEntity.State == EntityState.Deleted)
{
ObjectContext objContext = ((IObjectContextAdapter)this).ObjectContext;
var container = objContext.MetadataWorkspace.GetEntityContainer(objContext.DefaultContainerName, DataSpace.CSpace);
var objectStateEntry = ((IObjectContextAdapter)this).ObjectContext.ObjectStateManager.GetObjectStateEntry(myEntity.Entity);
var entityKeys = objectStateEntry.EntityKey.EntityKeyValues;
var entity = myEntity;
var hasAnyFk = false;
foreach (var entityKey in entityKeys)
{
if (hasAnyFk)
{
break;
}
var keyName = entityKey.Key;
foreach (var entitySet in container.EntitySets)
{
hasAnyFk = entitySet.ElementType.Members.Any(es => es.Name == keyName);
if (hasAnyFk)
{
break;
}
}
}
if (hasAnyFk)
{
var deletedProperty = myEntity.OriginalValues.PropertyNames.Where(p => myEntity.Property(p).Name == "Deleted").FirstOrDefault();
if (deletedProperty != null)
{
myEntity.State = EntityState.Modified;
myEntity.CurrentValues[deletedProperty] = true;
}
}
}
}
return base.SaveChanges(); }
答案 0 :(得分:0)
你可以处理这是SaveChanges
的重载:
public override int SaveChanges()
{
foreach (var entry in this.ChangeTracker.Entries().Where(e => e.State ==
System.Data.Entity.EntityState.Deleted).ToList())
{
var delPropName = "IsDeleted";
if (entry.OriginalValues.PropertyNames.Contains(delPropName))
{
var delProp = entry.Property(delPropName);
delProp.CurrentValue = true;
entry.State = System.Data.Entity.EntityState.Modified;
}
}
return base.SaveChanges();
}
此处,entry.OriginalValues.PropertyNames
用于检查实体中是否存在该属性,然后设置其值并将条目的状态更改为Modified
。请注意,我在应用this.ChangeTracker.Entries()
后循环遍历ToList()
,否则集合的内容会在循环播放时发生变化。