【发布时间】:2016-03-03 01:12:40
【问题描述】:
我正在手动更改一个实体,然后我试图验证我的 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 识别更改>”方法)?
【问题讨论】:
-
仔细阅读后,情况很简单,您有一个实体实例没有被实体框架跟踪。或 STE,在 EF6 上不再支持它
标签: c# entity-framework entity-framework-6