Click here to Skip to main content
15,937,602 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, can you please help me here. I am having this error, when I try to insert data. I have two tables with a foreign key relationship. I tried to debug the exception happens when it reaches cmd.ExecuteNonQuery();. Please help me.

SQL
CREATE TABLE TB_User
(
	UserId varchar(128) PRIMARY KEY NOT NULL,
	FirstName varchar(50) NOT NULL,
	LastName varchar (50) NOT NULL,
	Email varchar (128) NOT NULL,
	PhoneNumber varchar(15) NOT NULL,
	UserType varchar(50) NOT NULL,
	Password varchar (128) NOT NULL,
)


SQL
CREATE TABLE TB_Property
(
	PropertyId varchar(128) PRIMARY KEY NOT NULL,
	PropertyType varchar (128) NOT NULL,
	Area varchar(50) NOT NULL,
	Price decimal (18,0) NOT NULL,
	UserId varchar(128) FOREIGN KEY REFERENCES TB_User(UserId) NOT NULL
	
)


I got the current user id from query string, then after that, I tried to store the Id in property table. while debugging, I tried to check the query string, the Id exists already in the user table.
C#
if (Request.QueryString["UserId"].ToString() != null)
                {
                    currentUserId = Request.QueryString["UserId"].ToString();
}


This is the insertion query.
SQL
SqlCommand cmd = new SqlCommand("INSERT INTO TB_Property(PropertyId, PropertyType, Area, Price,UserId) VALUES(NEWID(), @PropertyType, @Area,@Price, '"+ currentUserId +"')", conn);
Posted
Comments
Karthik_Mahalingam 24-Dec-13 1:19am    
post your full ADO code...
Member 10215709 24-Dec-13 3:45am    
Here is the remaining code.

cmd.Parameters.AddWithValue("@PropertyType", propertyType);
cmd.Parameters.AddWithValue("@Area", area);
cmd.Parameters.AddWithValue("@Price", price);
cmd.Parameters.AddWithValue("@UserId", currentUserId);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();

the exception is when it reaches cmd.ExecuteNonQuery();

Hi if NEWID() is a method that return any value, then try this,

SQL
SqlCommand cmd = new SqlCommand("INSERT INTO TB_Property(PropertyId, PropertyType, Area, Price,UserId) VALUES('"+NEWID()+"', @PropertyType, @Area,@Price, '"+ currentUserId +"')", conn);



hope it helps,

Regards
Sameer
 
Share this answer
 
try and keep property id autogenerated from databse only using increment by 1. then you dont need to pass property id from the code. otherwise your code looks good.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900