无法从其他Entity容器中删除实体

时间:2015-10-25 07:23:06

标签: c# entity-framework

//Repository Method

public void Delete(int id)
{
    using (var scope = new UnitOfWork(_container))
    {
        var entity = AuthorService.GetById(id);
        scope.Container.Authors.DeleteObject(entity);
    }     
}

Ninject binding

public class LibraryManagerInjectModule : NinjectModule
{
    public override void Load()
    {
        Bind<LibManagerContainer>().To<LibManagerContainer>().InThreadScope();
    }
}

//Author Service Class

public static class AuthorService
{
    private static LibManagerContainer Container
    {
        get { return MF.MF.Get<LibManagerContainer>(); }
    }

    public static Author GetById(int id)
    {
        using (var scope = new UnitOfWork(Container))
        {
            return Container.Authors.SingleOrDefault(x => x.Id == id);
        }
    }

    public static Author GetByName(String name)
    {
        using (var scope = new UnitOfWork(Container))
        {
            return Container.Authors.SingleOrDefault(x => x.Name == name);
        }
    }
}

使用此代码我无法从数据库中删除实体。它向我显示一个错误,即实体不属于同一个对象状态管理器,但我在Threadscope中创建了libContainer对象,但从未能删除该实体。

2 个答案:

答案 0 :(得分:2)

您不需要从db加载实体来删除记录。 Id足以让人知道,它解决了另一个上下文问题:

var employer = new Employ { Id = 1 };
ctx.Employ.Attach(employer);
ctx.Employ.Remove(employer);
ctx.SaveChanges();

从这里采取:Delete a single record from Entity Framework?

P.S。您的架构有问题。应在一个范围内使用单个上下文。

答案 1 :(得分:1)

您用DataContext检索entity跟踪实体,以了解对其的更改。因此,您无法使用另一个保存从DataContext(或您的UnitOfWork)检索到的实体。
正如您在评论中提到的,删除应该是另一个事务。要实现此目的,您应该通过id删除,而不是删除对象 只需向RemoveById添加AuthorService方法:

public  static class AuthorService
{
    ...

    public static void RemoveById(int id)
    {
        using (var scope = new UnitOfWork(Container))
        {
            var author = Container.Authors.SingleOrDefault(x => x.Id == id);
            Container.Authors.Remove(author);
        }
    }
    ...