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

前端 未结 10 1205
终归单人心
终归单人心 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:35

    Just to propergate on Kjartans explanation:

    I had:

    public Project DeleteProject(int id)
        {
            using (var context = new Context())
            {
                var p = GetProject(id);
                context.Projects.Remove(p);
                context.SaveChanges();
                return p;
            }
        }
    

    The problem is that I used my own method (GetProject()) to get the entity (hence using another context to load the entity):

    public Project GetProject(int id)
        {
            using (var context = new Context())
            {
                var project = context.Projects
                    .Include(p => p.Reports.Select(q => q.Issues.Select(r => r.Profession)))
                    .Include(p => p.Reports.Select(q => q.Issues.Select(r => r.Room)))
                    .SingleOrDefault(x => x.Id == id);
                return project;      
            }
        }
    

    One solution could be to attach the loaded entity as Kjartan states, another could be mine solution, to load the entity within the same context:

    public Project DeleteProject(int id)
        {
            using (var context = new Context())
            {
                var p = context.Projects.SingleOrDefault(x => x.Id == id);
                if (p == null)
                    return p;
    
                context.Projects.Remove(p);
                context.SaveChanges();
                return p;
            }
        }
    

提交回复
热议问题