IT박스

ObjectStateManager에서 오브젝트를 찾을 수 없으므로 오브젝트를 삭제할 수 없습니다.

itboxs 2020. 7. 25. 10:43
반응형

ObjectStateManager에서 오브젝트를 찾을 수 없으므로 오브젝트를 삭제할 수 없습니다.


"ObjectStateManager에서 개체를 찾을 수 없으므로 개체를 삭제할 수 없습니다."라는 오류가 발생합니다.

내 코드는 다음과 같습니다

    protected MyEntities sqlEntities;

    public virtual void Delete(TEntity entity)
    {
        System.Type t = typeof(TEntity);
        sqlEntities.DeleteObject(entity);
        sqlEntities.SaveChanges();
    }

이는 엔티티가 연결되지 않았 음을 의미합니다 (동일한 컨텍스트 인스턴스에 의해로드되지 않음). 이 시도:

protected MyEntities sqlEntities;

public virtual void Delete(TEntity entity)
{
    sqlEntities.Attach(entity);
    sqlEntities.DeleteObject(entity);
    sqlEntities.SaveChanges();
}

에 그냥 작은 설명 라디 Mrnka에 의해 대답 (허용 대답해야한다).

나와 같은 경우 다음과 같은 형식의 코드가 있습니다.

using (var context = new MyDataContext())
{
    context.MyTableEntity.Remove(EntytyToRemove);
    var nrOfObjectsChanged = context.SaveChanges();
}

.. 그러고 싶은 일 :

using (var context = new MyDataContext())
{
    // Note: Attatch to the entity:
    context.MyTableEntity.Attach(EntityToRemove);

    context.MyTableEntity.Remove(EntityToRemove);
    var nrOfObjectsChanged = context.SaveChanges();
}

아마도 이것은 분명해 보이지만 처음에는 컨텍스트 뿐만 아니라 연결할 엔티티지정해야한다는 것이 분명 하지 않았습니다 .


Kjartans의 설명을 적절하게 설명하십시오.

나는했다 :

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;
        }
    }

I know this question is quite old but none of the above worked for me since i was deleting registers from more than one class/service and each of of them was instantiating it's own database connection context.

What i did to solve it was to send the first created context to the rest of the classes/services that where going to access the database.

For example, my serviceA was going to delete some of it's registers and call serviceB and serviceC to do the same with their registers.

I would then delete my registers on serviceA and pass as a parameter the context created on the serviceA to serviceB and serviceC.


You can write this code:

var x=yourquery.FirstOrDefault(); 

sqlEntities.DeleteObject(x);
sqlEntities.SaveChanges();

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

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


You should be sure that your object is exist in the list you are trying to remove from , you should put the following condition

if(context.entity.contains(your object))

remove it.

if you have a complicated condition for equality you should override equal method in entity class to put your condition for equality , to get the right way for an extension method "entity.contains"


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.


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

sqlEntities.Attach(entity);
sqlEntities.Remove(entity);
sqlEntities.SaveChanges();

참고URL : https://stackoverflow.com/questions/7791149/the-object-cannot-be-deleted-because-it-was-not-found-in-the-objectstatemanager

반응형