How to use DbContext.Database.SqlQuery(sql, params) with stored procedure? EF Code First CTP5

后端 未结 10 1935
梦谈多话
梦谈多话 2020-11-22 16:53

I have a stored procedure that has three parameters and I\'ve been trying to use the following to return the results:

context.Database.SqlQuery

        
10条回答
  •  星月不相逢
    2020-11-22 17:49

    @Tom Halladay's answer is correct with the mention that you shopuld also check for null values and send DbNullable if params are null as you would get an exception like

    The parameterized query '...' expects the parameter '@parameterName', which was not supplied.

    Something like this helped me

    public static object GetDBNullOrValue(this T val)
    {
        bool isDbNull = true;
        Type t = typeof(T);
    
        if (Nullable.GetUnderlyingType(t) != null)
            isDbNull = EqualityComparer.Default.Equals(default(T), val);
        else if (t.IsValueType)
            isDbNull = false;
        else
            isDbNull = val == null;
    
        return isDbNull ? DBNull.Value : (object) val;
    }
    

    (credit for the method goes to https://stackoverflow.com/users/284240/tim-schmelter)

    Then use it like:

    new SqlParameter("@parameterName", parameter.GetValueOrDbNull())
    

    or another solution, more simple, but not generic would be:

    new SqlParameter("@parameterName", parameter??(object)DBNull.Value)
    

提交回复
热议问题