【问题标题】:Entity Framework Code First Update a Single Property of a Complex Type实体框架代码首先更新复杂类型的单个属性
【发布时间】:2013-04-15 23:43:37
【问题描述】:

我的行为很奇怪。我想更新复杂类型的单个属性。当我指定要使用 IsModified 更新的属性时(有些属性为真,有些为假),我没有任何更新。如果我不指定复杂类型的属性,则会更新复杂属性的每个字段。

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))

如果我没有将 SubProperty2 的 IsModified 指定为 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();

【问题讨论】:

  • 我从来没有在复杂类型的属性上真正尝试过——但可能会反过来——先做false,然后是你希望更新的那些。还可以尝试在整个ComplexType 属性上设置false - 然后在单个子属性上设置true
  • 我做了几次测试都没有成功。但是感谢您的输入...

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多