dazza12345
Programmer
HI all, im in a bit of a pickle!
I have the following Data Function that will insert Addresses into an AddressDetails table. The first column in the table is an auto-incremented AddressID.
My problem is, how can i get the value fo the AddressID as soon as I have inserted the new row?
The SELECT SCOPE_IDENTITY() AS 'InsertedId' line of code is ment to return the AddressID. When inserting the SQL into the Sql Server query tool, the sql is successfully executed also the AddressID is returned successfully.
However, whenever i reach the line of code
it returns a Specified cast is not valid error.
Any ideas where im going wrong?
I have the following Data Function that will insert Addresses into an AddressDetails table. The first column in the table is an auto-incremented AddressID.
My problem is, how can i get the value fo the AddressID as soon as I have inserted the new row?
Code:
public static void CreateAddressDetails(AddressDetails addressdetails)
{
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Database"].ConnectionString))
{
using (SqlCommand command = new SqlCommand())
{
command.Connection = connection;
command.CommandText = "INSERT INTO AddressDetails " +
"(HouseNumber, AddressLine1, AddressLine2, City, County, Country, PostCode, IsCopy) " +
"VALUES(@HouseNumber, @AddressLine1, @AddressLine2, @City, @County, @Country, @PostCode, @IsCopy); SELECT SCOPE_IDENTITY() AS 'InsertedId';";
command.Parameters.AddWithValue("@HouseNumber", addressdetails.HouseNumber);
command.Parameters.AddWithValue("@AddressLine1", addressdetails.AddressLine1);
command.Parameters.AddWithValue("@AddressLine2", addressdetails.AddressLine2);
command.Parameters.AddWithValue("@City", addressdetails.City);
command.Parameters.AddWithValue("@County", addressdetails.County);
command.Parameters.AddWithValue("@Country", addressdetails.Country);
command.Parameters.AddWithValue("@PostCode", addressdetails.PostCode);
command.Parameters.AddWithValue("@IsCopy", addressdetails.IsCopy);
connection.Open();
int insertId = (int)command.ExecuteScalar();
}
}
}
The SELECT SCOPE_IDENTITY() AS 'InsertedId' line of code is ment to return the AddressID. When inserting the SQL into the Sql Server query tool, the sql is successfully executed also the AddressID is returned successfully.
However, whenever i reach the line of code
Code:
int insertId = (int)command.ExecuteScalar();
Any ideas where im going wrong?