I am searching for (PostId,UserId) into PostLikes table using SqlDataAdapter
, if the row is found , I am using SqlCommandBuilder.GetDeleteCommand()
to
There are a couple of issues:
SqlAdapter
for the SqlCommandBuilder
. Insert
/ Delete
commandsSqlCommandBuilder
, you then need to change the underlying dataset in order for any changes to be made to the table during the Update
.IDisposable
and should be disposed ASAP - using
scopes help here..
var postId = 1;
var userId = 1;
string msg;
using (var con = new SqlConnection(@"data source=..."))
using (var selectCommand = new SqlCommand(
"select LikeId, PostId, UserId from PostLikes WHERE PostId=@PostId AND UserId=@UserId", con))
using (var sqlDataAdapter = new SqlDataAdapter(selectCommand))
using (var ds = new DataSet())
{
con.Open();
selectCommand.Parameters.AddWithValue("@PostId", postId);
selectCommand.Parameters.AddWithValue("@UserId", userId);
sqlDataAdapter.Fill(ds, "Result");
using (var sqlCommandBuilder = new SqlCommandBuilder(sqlDataAdapter))
{
if (ds.Tables["Result"].Rows.Count == 1)
{
sqlDataAdapter.DeleteCommand = sqlCommandBuilder.GetDeleteCommand(true);
ds.Tables["Result"].Rows[0].Delete();
msg = "Data will be deleted";
}
else
{
sqlDataAdapter.InsertCommand = sqlCommandBuilder.GetInsertCommand(true);
// Null because LikeId is Identity and will be auto inserted
ds.Tables["Result"].Rows.Add(null, postId, userId);
msg = "Data will be inserted";
}
sqlDataAdapter.Update(ds, "Result");
}
}
I've assumed the following Schema:
CREATE TABLE PostLikes
(
LikeId INT IDENTITY(1,1) PRIMARY KEY,
PostId INT,
UserId INT
)
And I've assumed you want to 'toggle' the insertion or deletion of a row with the postId, userid
combination.