DBNull cast to (object) returns different value [closed]

…衆ロ難τιáo~ 提交于 2020-01-07 09:54:33

问题


I am trying to write DBNull.Value using Parameters.AddWithVallue when an optional parameter (a string) of a C# method is null.

public static void Abc(string distrito, string municipio = null)

command.Parameters.AddWithValue("@Municipio", municipio ?? (object)DBNull.Value);
command.Parameters.AddWithValue("@Municipio", municipio.Length > 0 ? municipio : (object)DBNull.Value);

However, (object)DBNULL returns two different values in two different working ways. One writes empty/null and other NULL.


回答1:


I'm going to make a few assumptions, but I think I know what's going on. municipio is probably an empty string. It is not null.

In that case, municipio ?? (object)DBNull.Value will be an empty string, not null. However, municipio.Length > 0 ? municipio : (object)DBNull.Value has a value of DBNull.Value, which will generate a null in SQL Server. In this case, if municipio is null, then this code will throw. Since you say the code runs, I'm assuming that municipio is not null.



来源:https://stackoverflow.com/questions/41473095/dbnull-cast-to-object-returns-different-value

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