Entity Framework 4.1: How do I delete by object Id

后端 未结 4 1577
梦毁少年i
梦毁少年i 2021-02-01 15:42

I would like to know how to delete an object from Entity Framework 4.1 without first having to load the object from the database. I have found these other 2 answers on Stack Ove

4条回答
  •  孤城傲影
    2021-02-01 16:22

    The following code works well for me:

    var c = db.Set().Find(id);
    db.Entry(c).State = EntityState.Deleted;
    db.SaveChanges();
    

    If this object wasn't tracked previously by the DbContext then it would hit the database, otherwise it would find it in memory.

提交回复
热议问题