UpdateNonDefaults is ignoring boolean parameters set to false

萝らか妹 提交于 2019-12-05 18:46:29

Please post your code, or we can't tell 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?

As a work-around, I have changed my "bool" data types to "string" and am using bool.FalseString and bool.TrueString to set my values. Not nice...

This is not the ideal solution but I used anonymous type as mentioned here to update the null-able boolean field and it worked.

One way to limit the fields which gets 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?

While you call the UpdateNonDefaults method, it generates sql via the method ToUpdateStatement 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);
}

Please note the line:

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!