实体框架代码首先更新复杂类型的单个属性

时间:2013-04-15 23:43:38

标签: c# entity-framework ef-code-first entity-framework-5 complextype

我有一种奇怪的行为。我想更新复杂类型的单个属性。当我指定要使用IsModified更新的属性(某些属性为true而某些属性为false)时,我没有更新任何内容。如果我没有指定复杂类型的属性,则复制属性的每个字段都会更新。

public class MyEntity
{
    public MyComplexClass Property1 { get; set; }
}

//... The code below doesn't work, in fact it update nothing
var entityLocal = this.Set<MyEntity>().Local.SingleOrDefault(d => d.Id == entity.Id);
if (entityLocal == null)
{
   entityLocal = this.Set<MyEntity>().Attach(entity);
}
this.ChangeTracker.Entries<MyEntity>().Single(d => d.Entity == entityLocal).State = EntityState.Modified;
this.Entry(entity).Property(s => s.Property1.SubProperty1).IsModified = true;
this.Entry(entity).Property(s => s.Property1.SubProperty2).IsModified = false;//This seam to remove all update of the complex type...?
this.SaveChanges();

这产生:

update [dbo].[MyEntity]
set @p = 0
where (([Id] = @0))

如果我没有将IsModified指定为SubProperty2的false,我在SQL分析器中有以下内容:

update [dbo].[MyEntity]
set [Property1_SubProperty1] = @0, [Property1_SubProperty2] = null
where (([Id] = @1))

为什么我在某些属性上指定“IsModified”没有更新任何内容?

修改

经过多次尝试,我可以确认,如果我检查这两行,当复杂类型的1个属性设置为IsModified为False时,整个复杂类型没有更新。

var entry = DatabaseContext.Entry(entity);
var namesOfChangedProperties = entry.CurrentValues.PropertyNames.Where(p => entry.Property(p).IsModified).ToArray();

如果我将任何属性设置为True,没有问题但是当1属性设置为false(IsModified)时,整个SubProperty不在namesOfChangedProperties变量中。

编辑2

我尝试使用具有相同结果的ComplexProperty。

this.ChangeTracker.Entries<MyEntity>().Single(d => d.Entity == entityLocal).State = EntityState.Modified;
this.Entry(entity).ComplexProperty(s => s.Property1).Property(d => d.SubProperty1).IsModified = true;
this.Entry(entity).ComplexProperty(s => s.Property1).Property(d => d.SubProperty2).IsModified = false;
this.SaveChanges();

1 个答案:

答案 0 :(得分:7)

这是EF改变复杂类型跟踪方式的限制。 EF不跟踪属性级别的更改,而只跟踪整个对象是否被修改。这是作为EF1的一部分构建的限制,尚未删除。一方面,对于那些希望进行更细粒度的变更跟踪的人来说,删除此限制会很好。但是,另一方面,将复杂对象视为不可变“值类型”通常被认为是最佳实践。对于此类值类型,始终设置整个对象,这使得更细粒度的更改跟踪变得不那么有用。此外,更细粒度的更改跟踪不是一个非常常见的功能,因此EF团队不太可能很快就会对其进行处理。