将可空的guid传递给存储过程

时间:2016-10-19 08:04:44

标签: c# sql sql-server entity-framework stored-procedures

当我在我的c#代码中将可空的guid参数传递给存储过程时。我得到例外:

  

System.Data.SqlClient.SqlException(0x80131904):语法不正确   '@customerGuid'。

var userNameSqlParam = new SqlParameter
{
    ParameterName = "userName",
    Value = userName,
    DbType = DbType.String
};

var customerGuidSqlParam = new SqlParameter
{
    ParameterName = "customerGuid",
    Value = customerGuid,
    DbType = DbType.Guid
};

var rows = _dbContext.Database
    .SqlQuery<CurrentUserContextWithoutCustomer>
        ("EXEC [dbo].[GetCurrentUserContext] @userName @customerGuid",
        userNameSqlParam, customerGuidSqlParam)
    .ToList();

因此,当我通过SQL事件探查器查看我得到的内容时

exec sp_executesql 
N'EXEC [dbo].[GetCurrentUserContext] @userName @customerGuid',
N'@userName nvarchar(4),@customerGuid uniqueidentifier',
@userName=N'gir1',@customerGuid=default

我在查询结尾处看到默认。它会产生问题。 有存储过程的标题

ALTER PROCEDURE [dbo].[GetCurrentUserContext]
    @userName nvarchar(100),
    @customerGuid uniqueidentifier
AS

如何将可空的guid作为存储过程参数传递给sql。

3 个答案:

答案 0 :(得分:5)

首先,您应该发送DBNull.Value而不是null

var customerGuidSqlParam = new SqlParameter
{
    ParameterName = "customerGuid",
    Value = (object)customerGuid ?? (object)DBNull.Value,
    DbType = DbType.Guid
};

您在查询中遗漏了一个逗号。

var rows = _dbContext.Database
    .SqlQuery<CurrentUserContextWithoutCustomer>
        ("EXEC [dbo].[GetCurrentUserContext] @userName, @customerGuid",
        userNameSqlParam, customerGuidSqlParam)
    .ToList();

答案 1 :(得分:1)

在存储过程中,将默认值设置为null

ALTER PROCEDURE [dbo].[GetCurrentUserContext]
    @userName nvarchar(100),
    @customerGuid uniqueidentifier = NULL
AS

答案 2 :(得分:0)

你可以将它放在C#end

Value = customerGuid == null ? (object)DBNull.Value : customerGuid.Value

并在存储过程结束时,如前面的答案所示:

  

@customerGuid uniqueidentifier = NULL

当为null时,它将传递null。如果有价值,你会在@customerGuid param中得到它。