UpdateNonDefaults is ignoring boolean parameters set to false

大兔子大兔子 提交于 2019-12-13 12:28:44

问题


I'm trying to update a record in my SQL server 2012 Express DB using UpdateNonDefaults. Boolean fields which are set to false are getting ignored as can be seen from the SQL statement.

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

Thanks in advance..


回答1:


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?




回答2:


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




回答3:


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?




回答4:


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



来源:https://stackoverflow.com/questions/13944659/updatenondefaults-is-ignoring-boolean-parameters-set-to-false

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