Jac*_*cek 1 c# sql sql-server stored-procedures entity-framework
当我在我的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();
Run Code Online (Sandbox Code Playgroud)
因此,当我通过SQL事件探查器查看我得到的内容时
exec sp_executesql
N'EXEC [dbo].[GetCurrentUserContext] @userName @customerGuid',
N'@userName nvarchar(4),@customerGuid uniqueidentifier',
@userName=N'gir1',@customerGuid=default
Run Code Online (Sandbox Code Playgroud)
我在查询结束时看到默认值.它会产生问题.有存储过程的标题
ALTER PROCEDURE [dbo].[GetCurrentUserContext]
@userName nvarchar(100),
@customerGuid uniqueidentifier
AS
Run Code Online (Sandbox Code Playgroud)
如何将可空的guid作为存储过程参数传递给sql.
首先你应该发送一个DBNull.Value而不是null
var customerGuidSqlParam = new SqlParameter
{
ParameterName = "customerGuid",
Value = (object)customerGuid ?? (object)DBNull.Value,
DbType = DbType.Guid
};
Run Code Online (Sandbox Code Playgroud)
并且您在查询中错过了逗号.
var rows = _dbContext.Database
.SqlQuery<CurrentUserContextWithoutCustomer>
("EXEC [dbo].[GetCurrentUserContext] @userName, @customerGuid",
userNameSqlParam, customerGuidSqlParam)
.ToList();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3414 次 |
| 最近记录: |