[英]Entity Framework Code First: Computed property of type Type causes ArgumentNullException on Update-Database
[英]Entity Framework Code First Update a Single Property of a Complex Type
我有一種奇怪的行為。 我想更新復雜類型的單個屬性。 當我指定要使用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))
如果我沒有將SubMperty2的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變量中。
我嘗試使用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();
這是EF改變復雜類型跟蹤方式的限制。 EF不會在屬性級別上跟蹤更改,而只會跟蹤整個對象是否已修改。 這是作為EF1的一部分構建的限制,尚未刪除。 一方面,對於那些希望進行更詳細的變更跟蹤的人來說,消除此限制將是一件好事。 但是,另一方面,將復雜對象視為不可變的“值類型”通常被認為是最佳實踐。 對於此類值類型,始終設置整個對象,這使得更細粒度的更改跟蹤變得不那么有用。 同樣,更細粒度的變更跟蹤也不是普遍要求的功能,因此EF團隊不太可能很快對其進行工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.