The object cannot be deleted because it was not found in the ObjectStateManager

前端 未结 10 1199
终归单人心
终归单人心 2020-11-27 14:48

I am getting this error \"The object cannot be deleted because it was not found in the ObjectStateManager.\"

My code is:

    protected MyEntities sql         


        
相关标签:
10条回答
  • 2020-11-27 15:47

    I got this problem and solve it. Just copy below code:

    sqlEntities.Attach(entity);
    sqlEntities.Remove(entity);
    sqlEntities.SaveChanges();
    
    0 讨论(0)
  • 2020-11-27 15:48

    In case none of the above worked, you may try this solution:

    context.Entry(yourObject).State = System.Data.Entity.EntityState.Deleted; context.SaveChanges();

    0 讨论(0)
  • 2020-11-27 15:52

    You can write this code:

    var x=yourquery.FirstOrDefault(); 
    
    sqlEntities.DeleteObject(x);
    sqlEntities.SaveChanges();
    
    0 讨论(0)
  • 2020-11-27 15:52

    Make sure the model passing into Remove(Entity) is exactly same as the database record.

    Some times its possible to pass the model with out some fields like Id or Date. keep those into @html.Hiddenfor if you posting as form.

    Best way is to pass the ID and get the entity using Find(Id) method and pass that to Remove(Entity)

    Hope this helps someone.

    0 讨论(0)
提交回复
热议问题