I am searching for (PostId,UserId) into PostLikes table using SqlDataAdapter
,if the row is found , I am using SqlCommandBuilder.GetDeleteCommand()
to generate the delete instruction and deleting the underlying row , if row is not found ,using SqlCommandBuilder.GetInsertCommand()
to generate the insert command and inserting the row to the table using SqlDataAdapter.Update()
. But the row is not getting inserted to the table in database.Here is what I have done so far
SqlConnection con = new SqlConnection(connectionStrings);
SqlDataAdapter sqlDataAdapter=new SqlDataAdapter("select * from PostLikes where PostId like "+postlike.PostId+" and UserId like "+postlike.UserId,con);
DataSet ds = new DataSet();
sqlDataAdapter.Fill(ds, "Result");
con.Open();
SqlCommandBuilder sqlCommandBuilder = new SqlCommandBuilder(sqlDataAdapter);
if(ds.Tables["Result"].Rows.Count==1)
{
sqlDataAdapter.DeleteCommand = sqlCommandBuilder.GetDeleteCommand(true);
msg = "Data is deleted";
}
else
{
sqlDataAdapter.InsertCommand = sqlCommandBuilder.GetInsertCommand(true);
msg = "Data is inserted";
}
sqlDataAdapter.Update(ds, "Result");
and the table
PostLikes(LikeId,PostId,UserId)
There are a couple of issues:
SqlAdapter
for theSqlCommandBuilder
.Insert
/Delete
commandsSqlCommandBuilder
, you then need to change the underlying dataset in order for any changes to be made to the table during theUpdate
.IDisposable
and should be disposed ASAP -using
scopes help here..
I've assumed the following Schema:
And I've assumed you want to 'toggle' the insertion or deletion of a row with the
postId, userid
combination.