1

I am trying to delete all table data where username = current user name. But there is some error on lambda expression and conversion."Cannot convert source type to target type. Any help?

public JsonResult DeleteChatMessages(int id)
        {
            string toId = Session["SessionUserName"].ToString();
            tblChat tblchats = _obj.tblChat.Where(p => p.ToId == toId);
            _obj.tblChat.Remove(tblchats);
            _obj.SaveChanges();
            return this.Json(true, JsonRequestBehavior.AllowGet);
        }
1
  • 1
    Change your line as tblChat tblchats = _obj.tblChat.FirstOrDefault(p => p.ToId == toId) Commented Feb 3, 2015 at 7:28

2 Answers 2

3

I am assuming you are expecting only one object to return from the Where filter. Change your line as,because as per this . The Where clause returns an IEnumerable<TSource>. And you are assigning that to the non IEnumerable object.

  tblChat tblchats = _obj.tblChat.FirstOrDefault(p => p.ToId == toId)

and you also might want to check for the Null, before removing it from the tblChat.

If you are expecting more than one object to match the filter and want to remove all of them then use @tmg approach.

    _obj.tblChat.RemoveRange(_obj.tblChat.Where(p => p.ToId == toId).ToList());
Sign up to request clarification or add additional context in comments.

Comments

2

Filter the "chats" you want.

 var tblchats = _obj.tblChat.Where(p => p.ToId == toId).ToList();

After iterate throught them and remove.

    foeach(chat in tblchats){
        _obj.tblChat.Remove(chat);
    }
    _obj.SaveChanges();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.