I have two tables, for simplicity lets pretend they’re defined like this
Stack
{
ID int Primary Key
Name varchar(255), not null
}
User
{
ID int Primary Key
Name varchar(255), not null
Stack_ID int, Foreign Key to Stack.ID nulls are allowed
}
My stored procedure for inserting a User looks something like this
CREATE PROCEDURE usp_insertUser
@id int,
@name varchar(255),
@stackID int
AS
INSERT INTO User (ID, Name, Stack_ID) VALUES (@id, @name, @stackID)
GO
In my Model layer my user class I use a nullable to hold StackID
public class User
{
public int ID {get; set;}
public string Name {get; set;}
int? Stack_ID {get; set;}
}
My Data Access Layer I thought was pretty standard, but i’m having trouble, my InsertUser method looks something similar to this
public void InsertUser(User entity)
{
...
using (SqlCommand command = new SqlCommand())
{
command.Connection = conn;
command.CommandType = System.Data.CommandType.StoredProcedure;
command.CommandText = "usp_insertUser";
command.Parameters.AddWithValue("@id", entity.ID);
command.Parameters.AddWithValue("@name", entity.Name);
command.Parameters.AddWithValue("@stackID", entity.Stack_ID);
conn.Open();
...
//real stored proc returns the id of the item inserted so i use a reader
SqlDataReader reader = command.ExecuteReader();
....
}
}
My problem here, when I leave User.Stack_ID null, it doesn’t insert a null in the database, instead I get an error, saying that @stackID was expected but wasn’t there. Why can’t I just straight up insert this nullable int into the database?
Also, is there some one line way I could read this possible null int from the database?
When I did this I assumed this would work.
User.Stack_ID = (int?)reader["Stack_ID"];
that obviously doesn’t work, and I have to do something sloppy like
try {
User.StackID = (int)reader["Stack_ID"];
}
catch {
User.StackID = null;
}
any help would be appreciated with working with these Nullable type. Sorry for the noob questions, in the past when I had ints and wanted a null value or w/e I would set them to -1 or 0 or something, that doesn’t work when they’re foreign keys 🙁
To read a null value, you could do this:
This uses the
Fieldextension method. From MSDN: