Processing When ASP. NET uses a stored procedure with null parameters

Source: Internet
Author: User

When writing a stored procedure for inserting a new record, the parameters of the stored procedure generally correspond to the attributes of the object class. However, when receiving data at the front end, you do not need all object class attributes. In this way, some attributes are not assigned a value. If these attributes are of the reference type and are not initialized, problems may occur when assigning values to stored procedure parameters. This is because the null type in the database corresponds to the DBNull type in. net instead of the null type, and DBNull cannot be automatically converted to null.

Solution:

1. Add the default value (initialization) when defining attributes of the object class ).

Reference content is as follows:
Class info
{
String _ a = ""; // initialize the reference type variable
Int _ B; // The value type does not require initialization.
 
Public string
{
Get {return _ ;}
Set {_ a = value ;}
}
Public int B
{
Get {return _ B ;}
Set {_ B = value ;}
}
}

2. When assigning values to stored procedure parameters:

Reference content is as follows:
Cmd. Parameters. Add ("@ a", _ info. A = null? "": _ Info. );

3. assign default values to parameters during SQL server storage:

Reference content is as follows:
CREATE proc
(
@ A varchar (50) = null,
@ B varchar (50) = null
)
As
Insert into info (a, B) values (@ a, @ B)
GO

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.