Reputation: 535
I am creating a project that includes a like button. It's all working up until the delete record.
long delete returns the correct ID in the database. Here's the code. I'm obviously using the db.Likes.Remove(delete) the wrong way.
public ActionResult LikePicture(int userID, int pictureID)
{
Picture picture = new Picture();
bool liked = picture.LikePicture(userID, pictureID);
if (liked == true) //Remove Like
{
long delete = (from like in db.Likes
where userID == like.UserID && pictureID == like.PictureID
select like.LikeID).SingleOrDefault();
// Remove like from database
**db.Likes.Remove(delete);
}
else
{
// Add like to database
}
return RedirectToAction("Index");
}
I was looking for a db.Likes.DeleteOnSubmit() but intelesense didn't give me the option so I tried the remove. As in all my questions I will say, I am new to C# so please keep it simple =) Thanks.
Upvotes: 0
Views: 105
Reputation: 101742
Don't select the ID
if you want to delete your item select your item
var item = (from like in db.Likes
where userID == like.UserID && pictureID == like.PictureID
select like).FirstOrDefault();
And you can use FirstOrDefault
to avoid exception, then check for null and Remove
the item:
if(item != null)
{
db.Likes.Remove(item);
db.SaveChanges();
}
Upvotes: 4