我正在手动更改实体,之后我试图验证在我的DbContext中是否有与我的更改匹配的实体。我预期的“答案”是“真实的”,但它是“错误的”。 由于我的代码是非常复杂的,有许多规则,我创建了一个简单的例子来试图解释这个问题:手动进行的实体更改未被EntityFramework识别
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“缓存”。
但是,有没有办法强制的EntityFramework使用IQueryable的扩展方法(如“任何”和“FirstOrDefault”方法)找出发生的变化,当我查询中的DbContext的实体?
更仔细地阅读后,情况很简单,你有一个实体实例不是由实体框架跟踪。或STE,它不再支持EF6 – mijail