UpdateNonDefaults ignores boolean parameters set to false

I am trying to update a record in my SQL Server 2012 Express DB using UpdateNonDefaults. Logical fields that are set to false are ignored, as seen in the SQL statement.

How to set DB value to false for boolean fields using UpdateNonDefaults?

Thanks in advance.

+4
source share
4 answers

Please post your code, or we cannot say what is wrong ...

Try:

[Default(typeof(bool?), null)] public bool? Foo {get;set;} 

Or try:

 [Default(typeof(int?), null)] public int? Foo {get; set;} 

See if it works?

0
source

As a job, I changed my bool data types to string and use bool.FalseString and bool.TrueString to set my values. Not nice ...

0
source

This is not an ideal solution, but I used the anonymous type mentioned here to update the null logical field and it worked.

One way to restrict fields that are being updated is to use an anonymous Type:

 db.Update<Person>(new { FirstName = "JJ" }, p => p.LastName == "Hendrix"); 

Does anyone know why UpdateNonDefaults does not update boolean values ​​to false?

0
source

While you call the UpdateNonDefaults method, it generates sql through the ToUpdateStatement method in SqlExpression.cs

 public virtual string ToUpdateStatement(T item, bool excludeDefaults = false) { var setFields = new StringBuilder(); foreach (var fieldDef in modelDef.FieldDefinitions) { if (fieldDef.ShouldSkipUpdate()) continue; if (fieldDef.IsRowVersion) continue; if (updateFields.Count > 0 && !updateFields.Contains(fieldDef.Name)) continue; // added var value = fieldDef.GetValue(item); if (excludeDefaults && (value == null || value.Equals(value.GetType().GetDefaultValue()))) continue; //GetDefaultValue? fieldDef.GetQuotedValue(item, DialectProvider); if (setFields.Length > 0) setFields.Append(", "); setFields .Append(DialectProvider.GetQuotedColumnName(fieldDef.FieldName)) .Append("=") .Append(DialectProvider.GetQuotedValue(value, fieldDef.FieldType)); } return string.Format("UPDATE {0} SET {1} {2}", DialectProvider.GetQuotedTableName(modelDef), setFields, WhereExpression); } 

Pay attention to the line:

 if (excludeDefaults && (value == null || value.Equals(value.GetType().GetDefaultValue()))) continue; //GetDefaultValue? 

When you update a value with a boolean value from true to false, here the value is fasle , and value.GetType () is actually typeof (bool) , not typeof (bool?) , So value.GetType (). GetDefaultValue () is always false. Then this column is ignored ...

0
source

All Articles