在EF数据访问层,一个实体对象不能被多个IEntityChangeTracker实例引用

本文关键字:不能 对象 实体 引用 实例 IEntityChangeTracker 一个 访问 数据 EF | 更新日期: 2023-09-27 18:09:11

我已经看到了很多关于相同主题的问题,但到目前为止还没有找到解决方案。给我带来问题的代码是:

    public async Task<IHttpActionResult> Post(FullOrderViewModel fullOrder)
    {
        //Get all order items
        List<OrderItem> orderItems = new List<OrderItem>();
        foreach (var oi in fullOrder.Order)
        {
            var color = _colorRepo.Find(oi.ColorId);
            var item = new OrderItem
            {
                Quantity = oi.Quantity,
                Color = color
            };
            orderItems.Add(item);
        }
        //Get customer id
        var customer = await _adminRepo.GetCustomerByUserName(fullOrder.Customer.UserName);
        var billAddress = _addressRepo.All.FirstOrDefault(x => x.AddressLine == fullOrder.BillingAddress.AddressLine && x.PostalCode == fullOrder.BillingAddress.PostalCode);
        var deliveryAddress = _addressRepo.All.FirstOrDefault(x => x.AddressLine == fullOrder.DeliveryAddress.AddressLine && x.PostalCode == fullOrder.DeliveryAddress.PostalCode);
        //CASE : sample order
        if (fullOrder.OrderType == OrderType.Sample)
        {
            var order = new SampleOrder {
                Type = OrderType.Sample,
                Status = "Unauthorized",
                Origin = Origin.Online,
                OrderItems = orderItems,
                CreationDate = DateTime.Now,
                CustomerId = customer.Id,
                BillAddressId = billAddress.AddressId,
                DeliveryAddressId = deliveryAddress.AddressId
            };
            try
            {
                _sampleOrderRepo.InserGraph(order);
                _unitOfWork.Save();
            }
            catch (Exception e)
            {
                return InternalServerError(e);
            }

我获得存储库的方式是通过OrderController构造函数中的依赖注入,所以我相信这是一种标准方式。我的每个repos都是这样构建的:

public class SampleOrderRepository : EntityRepository<SampleOrder, IPhoeniceUnitOfWork<PhoeniceContext>>, ISampleOrderRepository
{
    public SampleOrderRepository(IPhoeniceUnitOfWork<PhoeniceContext> unitOfWork) : base(unitOfWork)
    {
    }
    protected override IDbSet<SampleOrder> List(IPhoeniceUnitOfWork<PhoeniceContext> unitOfWork)
    {
        return unitOfWork.Context.SampleOrders;
    }
    protected override Expression<Func<SampleOrder, bool>> FindInt(int id)
    {
        return x => x.OrderId == id;
    }
}

重写通用实体存储库中的方法:

public abstract class EntityRepository<T, TContext> : IEntityRepository<T> 
    where T : class, IObjectWithState
    where TContext : IUnitOfWork<EntityContext>
{
    protected readonly TContext _unitOfWork;
    protected EntityRepository(TContext unitOfWork)
    {
        _unitOfWork = unitOfWork;
    }
    protected virtual IDbSet<T> List(TContext unitOfWork)
    {
        throw new NotImplementedException("List operation not implemented!");
    }
    protected virtual Expression<Func<T, bool>> FindInt(int id)
    {
        throw new NotImplementedException("Finding entity with an int is not implemented!");
    }
    protected virtual Expression<Func<T, bool>> FindString(string id)
    {
        throw new NotImplementedException("Finding entity with an int is not implemented!");
    }
    public virtual IQueryable<T> All { get { return List(_unitOfWork); } }
    public virtual IQueryable<T> AllIncluding(params Expression<Func<T, object>>[] includeProperties)
    {
        return includeProperties.Aggregate(All, (current, includeProperty) => current.Include(includeProperty));
    }
    public virtual T Find(int id)
    {
        return All.FirstOrDefault(FindInt(id));
    }
    public virtual T FindByString(string id)
    {
        return All.FirstOrDefault(FindString(id));
    }
    public virtual void InserGraph(T entity)
    {
        List(_unitOfWork).Add(entity);
    }
    public void InsertOrUpdate(T entity)
    {
        if (entity.ObjectState == State.Added) // New entity
        {
            _unitOfWork.Context.Entry(entity).State = EntityState.Added;
        }
        else        // Existing entity
        {
            _unitOfWork.Context.Entry(entity).State = EntityState.Modified;
            _unitOfWork.Context.ApplyStateChanges();
        }
    }
    public virtual void Delete(int id)
    {
        var entity = Find(id);
        List(_unitOfWork).Remove(entity);
    }
    public void Dispose()
    {
    }
}

最后这是我的UnitOfWork项目:

public class PhoeniceUnitOfWork : IPhoeniceUnitOfWork<PhoeniceContext>
{
    private readonly PhoeniceContext _context;
    public PhoeniceUnitOfWork() : base()
    {
        _context = new PhoeniceContext();
    }
    //Left for testing purposes
    public PhoeniceUnitOfWork(PhoeniceContext context)
    {
        _context = context;
    }
    public int Save()
    {
        return _context.SaveChanges();
    }
    public void Dispose()
    {
        _context.Dispose();
    }
    public IAddressRepository AddressRepository
    {
        get { return new AddressRepository(this); }
    }
    public IColorRepository ColorRepository
    {
        get { return new ColorRepository(this); }
    }
    public IHideOrderRepository HideOrderReposiotory
    {
        get { return new HideOrderRepository(this); }
    }
    public ISampleOrderRepository SampleOrderRepository
    {
        get { return new SampleOrderRepository(this); }
    }
    public ITaxonomyRepository TaxonomyRepository
    {
        get { return new TaxonomyRepository(this); }
    }
    PhoeniceContext IUnitOfWork<PhoeniceContext>.Context
    {
        get { return _context; }
    }
}

和我使用的上下文

public class PhoeniceContext : EntityContext
{
    // You can add custom code to this file. Changes will not be overwritten.
    // 
    // If you want Entity Framework to drop and regenerate your database
    // automatically whenever you change your model schema, add the following
    // code to the Application_Start method in your Global.asax file.
    // Note: this will destroy and re-create your database with every model change.
    // 
    // System.Data.Entity.Database.SetInitializer(new System.Data.Entity.DropCreateDatabaseIfModelChanges<Phoenice.EntityFramework.Models.PhoeniceContext>());
    public PhoeniceContext()
        : base("Phoenice")
    {
        Database.SetInitializer<PhoeniceContext>(new DropCreateIfChangeInitializer());
        //Database.SetInitializer<PhoeniceContext>(new DropCreateDatabaseAlways());
    }
    public DbSet<Address> Addresses { get; set; }
    public DbSet<SampleOrder> SampleOrders { get; set; }
    public DbSet<HideOrder> HideOrders { get; set; }
    public DbSet<OrderItem> OrderItems { get; set; }
    public DbSet<Color> Colors { get; set; }
    public DbSet<Taxonomy> Taxonomies { get; set; }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //There is OnModelCreating already overwritten in IdentityDbContext 
        //with all details required for ASP.NET identity
        base.OnModelCreating(modelBuilder);
        //solution for this mapping: http://stackoverflow.com/questions/11632951/primary-key-violation-inheritance-using-ef-code-first
        modelBuilder.Entity<SampleOrder>()
            .HasKey(x => x.OrderId)
            .Map(m =>
            {
                //Requires EF 6.1
                m.MapInheritedProperties();
                m.ToTable("SampleOrders");
            })
            .Property(x => x.OrderId)
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        modelBuilder.Entity<HideOrder>().Map(m =>
        {
            //Requires EF 6.1
            m.MapInheritedProperties();
            m.ToTable("HideOrders");
        });
        modelBuilder.Entity<HideOrder>().HasKey(x => x.OrderId);
    }
}

我知道我展示了很多代码,但希望这些都是数据访问层的构建块。出于某种原因,当我在SampleOrders上调用InsertGraph方法时,我得到"一个实体对象不能被IEntityChangeTracker的多个实例引用"异常。我把这段代码看了几十遍,还是不明白为什么会抛出这个错误消息

在EF数据访问层,一个实体对象不能被多个IEntityChangeTracker实例引用

我不确定我的答案,但我建议你如下:

我的版本的实体框架是有点不同,所以我不确定你会有所有需要的功能。当你这样做

List<OrderItem> orderItems = new List<OrderItem>(); foreach (var oi in fullOrder.Order) { var color = _colorRepo.Find(oi.ColorId); var item = new OrderItem { Quantity = oi.Quantity, Color = color }; orderItems.Add(item); }

我认为你应该首先分离所有的oi对象然后代码应该像

这样
List<OrderItem> orderItems = new List<OrderItem>();
    foreach (var oi in fullOrder.Order)
    {
        //detach oi
         //attach oi
        var color = _colorRepo.Find(oi.ColorId);
        var item = new OrderItem
        {
            Quantity = oi.Quantity,
            Color = color
        };
        orderItems.Add(item);
    }

orderItems中的项包含color。返回值:

_colorRepo.Find(oi.ColorId);

colorRepo保存了color的实体。

下一行的顺序由另一个repo使用,但在'order'中有来自前一个repo的颜色。

   _sampleOrderRepo.InserGraph(order);

两个repo持有相同的实体对象,从而导致此异常。

要避免这个问题,你可以做两件事:

每次使用_colorRepo.Find():

创建一个新的Color对象
var color = new Color()
{
     id = oi.ColorId
}

或通过将功能移动到服务

来只使用一个repo
相关文章: