我正在手动更改一个实体,之后我试图验证我的 DbContext 中是否有任何实体与我的更改相匹配。我期望的“答案”是“真”,然而却是“假”。 由于我的代码非常复杂并且有很多规则,我创建了一个简单的示例来尝试解释问题:
var propertyValues = new Dictionary<string, object>()
{
{"MyProperty1", "My value"},
{"MyProperty2", 10}
};
var entityId = 13;
var entityType = typeof(MyEntity);
// Applies the changes
this.ApplyChanges(db, entityType, entityId, propertyValues);
// This is "false"
var hasEntityWithValue = db.MyEntity.Any(p => p.Id == entityId && p.MyProperty1 != null);
// The "myEntity" is null
var myEntity = db.MyEntity.FirstOrDefault(p => p.Id == entityId && p.MyProperty1 != null);
// Gets the entity only by Id
myEntity = db.MyEntity.FirstOrDefault(p => p.Id == entityId);
// And when I compare the "MyProperty1" it's "true". Why?????
hasEntityWithValue = myEntity.MyProperty1 != null;
“ApplyChanges”方法:
private void ApplyChanges(DbContext db, Type entityType, int entityId,
Dictionary<string, object> propertyValues)
{
var entity = db.Set(entityType).Find(entityId);
foreach (var propertyValue in propertyValues)
{
var propertyInfo = entityType.GetProperty(propertyValue.Key);
// Sets the value
propertyInfo.SetValue(entity, propertyValue.Value);
}
db.ChangeTracker.DetectChanges();
}
我相信这种情况正在发生,因为当我查询实体时,我是在数据库而不是 EntityFramework“缓存”中查询它们。
但是当我使用 IQueryable 扩展方法(例如“Any”和“FirstOrDefault”查询 DbContext 中的实体时,有没有办法强制 EntityFramework 识别更改>”方法)?
最佳答案
你是对的。当您使用“Any”、“FirstOrDefault”或任何其他查找数据的 Linq 扩展方法时,将使用 SQL 查询。因此,除非您调用“SaveChanges”,否则不会看到对对象的任何更改(出于过滤目的)。
有一种方法可以查看物化对象,但您必须手动执行。您必须仅对物化对象进行 Linq-to-Objects 查询,以查看您想要的内容是否存在。然后,如果不是,则进行常规的 Linq-to-Entities 查询以在数据库中搜索它。不要混合这些查询,否则你可能会释放 hell 。
搜索物化对象:
context.ChangeTracker.Entries<MY_ENTITY>(); // strongly-typed, just an objects set
或
context.ChangeTracker.Entries(); // everything
关于c# - EntityFramework 未识别手动进行的实体更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35735054/