c# - EntityFramework 未识别手动进行的实体更改

标签 c# entity-framework entity-framework-6

我正在手动更改一个实体,之后我试图验证我的 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/

相关文章:

.net - 如何使用 Entity Framework 6.1 正确标记标识列?

C# - 这两种实例化类属性的方式有什么区别?

c# - 'enumType' 和 'TEnum' 之间的区别

entity-framework - Entity Framework 代码先迁移到多个数据库

c# - 无法在 Entity Framework 6 中一对一映射

c# - 同一列上具有多个外键的 Entity Framework 核心

c# - 如何使用对象上下文在 Entity Framework 中使用批量插入?

c# - 如何在 C# PresentationFramework.dll 中设置断点?

c# - BindingContext 和多选数据 GridView

c# - 根据方法参数构建 IQueryable