使用LINQ防止存储过程中的可为空参数

时间:2021-08-24 02:07:26

I want to define stored procedure parameters which do not allow null arguments.

我想定义不允许空参数的存储过程参数。

alt text http://www.pixelshack.us/images/xg3mr2xw0q13z22nal.jpg

替代文字http://www.pixelshack.us/images/xg3mr2xw0q13z22nal.jpg

That @MailItemId int OUTPUT will be not nullable because when I import the stored procedure into the LINQ to SQL designer it says @MailIetmid is ref int? mailItemId.

@MailItemId int OUTPUT将不可为空,因为当我将存储过程导入LINQ to SQL设计器时,它说@MailIetmid是ref int? mailItemId。

alt text http://www.pixelshack.us/images/er80hukg27lreiy9b83y.jpg

alt text http://www.pixelshack.us/images/er80hukg27lreiy9b83y.jpg

Thanks.

4 个解决方案

#1


If nothing else, you can just modify the auto-generated code (in designer.cs) to not accept a nullable integer. If the parameter ever does end up being null, it will probably cause a weird exception down in the LINQ to SQL code, but that's not a huge deal.

如果没有别的,你可以修改自动生成的代码(在designer.cs中)以不接受可以为空的整数。如果参数最终变为null,则可能会在LINQ to SQL代码中导致奇怪的异常,但这并不是什么大问题。

#2


No, you can't do this. Types in SQL Server can always be NULL.

不,你不能这样做。 SQL Server中的类型始终为NULL。

#3


You could create a function instead that returns an INT.

您可以创建一个返回INT的函数。

On the other hand, it is possible from SQL point of view that a NULL can be returned from function. I don't know how code generator will generate function for that. If it still returns a nullable int, I don't think it could be possible.

另一方面,从SQL的角度来看,可以从函数返回NULL。我不知道代码生成器将如何生成函数。如果它仍然返回一个可以为空的int,我认为它不可能。

#4


You can specify a default value instead:

您可以指定默认值:

@MailItemId int OUTPUT = 0

or something like that

或类似的东西

#1


If nothing else, you can just modify the auto-generated code (in designer.cs) to not accept a nullable integer. If the parameter ever does end up being null, it will probably cause a weird exception down in the LINQ to SQL code, but that's not a huge deal.

如果没有别的,你可以修改自动生成的代码(在designer.cs中)以不接受可以为空的整数。如果参数最终变为null,则可能会在LINQ to SQL代码中导致奇怪的异常,但这并不是什么大问题。

#2


No, you can't do this. Types in SQL Server can always be NULL.

不,你不能这样做。 SQL Server中的类型始终为NULL。

#3


You could create a function instead that returns an INT.

您可以创建一个返回INT的函数。

On the other hand, it is possible from SQL point of view that a NULL can be returned from function. I don't know how code generator will generate function for that. If it still returns a nullable int, I don't think it could be possible.

另一方面,从SQL的角度来看,可以从函数返回NULL。我不知道代码生成器将如何生成函数。如果它仍然返回一个可以为空的int,我认为它不可能。

#4


You can specify a default value instead:

您可以指定默认值:

@MailItemId int OUTPUT = 0

or something like that

或类似的东西