2010-09-01 60 views
0

對可空布爾屬性的更改不會保存回EF4中的數據庫,但其他可爲空的字段在更新時不會有任何問題。例如,如果我執行類似下面的簡單查詢:更新實體框架中的可空布爾字段

EmployeeSurvey employeeSurvey = context.EmployeeSurveys.SingleOrDefault(s => s.EmployeeSurveyID == 60); 

employeeSurvey.EmployeeSmokes = true; 
employeeSurvey.OtherComments = "Test comment"; 

context.SaveChanges(); 

更改已成功儲存到數據庫的OtherComments但是EmployeeSmokes性質的變化都沒有。 EmployeeSmokes屬性是一個布爾值?和其他可空布爾字段有相同的問題。

此外,只有在更改/更新現有的EmployeeSurvery記錄時纔會出現問題 - 創建/插入新的EmployeeSurveys時,包括EmployeeSmokes在內的所有屬性均成功保存。

我也嘗試使用ApplyCurrentValues方法根據this thread,但不幸的是它沒有幫助。

任何想法爲什麼會發生這種情況?

+0

您的代碼是正確的。問題在別處(不在你的問題中)。這對我有用。您需要更多地進行調試。嘗試SQL跟蹤。 – 2010-09-01 12:43:14

+0

我遇到了像你一樣的問題,但它是可空的整數。從我設法測試的時候,當你在數據庫中添加實體並且該字段被設置爲** null **時,在那之後你將不能使用EF來更新它...所以我想這是某種錯誤。我會繼續搜索,如果我找到答案,我會發佈一個答案。 – 2011-07-04 07:43:22

回答

0

employeeSurvey.EmployeeSmokes在數據庫中的價值是什麼?如果確實如此,則EF會注意到沒有更改,並在生成的更新SQL中省略它,因爲沒有更改(可以在SQL Profiler中驗證此更改)。

0

發表評論幾分鐘後,我發現我的問題的解決方案,如果你仍然需要這個,也可以幫助你。

我正在使用自我跟蹤實體,並且必須在生成的模板中添加一些代碼。在UpdateOriginalValues(ObjectContext的上下文中,IObjectWithChangeTracker實體)方法添加以下片段:

foreach(EdmProperty property in entityType.Properties) 
    { 
     object value; 
     if(property.TypeUsage.EdmType is PrimitiveType && entity.ChangeTracker.OriginalValues.TryGetValue(property.Name, out value)) 
     { 
      //START OF EDIT 
      if (value == null && property.Nullable) 
      { 
       var currentValues = entry.CurrentValues; 
       int ordinal = currentValues.GetOrdinal(property.Name); 
       var temp = currentValues[ordinal]; 
       currentValues.SetDBNull(ordinal); 
       entry.ApplyOriginalValues(entity); 
       currentValues.SetValue(ordinal, temp); 
      } 
      //END OF EDIT 
      originalValueRecord.SetValue(property, value); 
     } 
     else if(property.TypeUsage.EdmType is ComplexType) 
     { 
      OriginalValueRecord complexOriginalValues = originalValueRecord.GetOriginalValueRecord(property.Name); 
      UpdateOriginalValues((ComplexType)property.TypeUsage.EdmType, entity.GetType().FullName, property.Name, entity.ChangeTracker.OriginalValues, complexOriginalValues); 
     } 
    } 

的原始源是HERE。我希望這會很有用!