entity framework“实体对象不能被IEntityChangeTracker的多个实例引用”
我收到了错误
IEntityChangeTracker的多个实例不能引用实体对象
尝试创建新实体并将其保存到数据库时。
我理解错误以及它是如何正常发生的,但在这种情况下,我所做的只是创建一个新实体并在保存之前向其添加一些int
,而不是从其他上下文添加任何其他实体。
我已经包含了导致错误的函数。 正如您所看到的那样,它正在传递一个EndProduct
,它是一个被_billableRepository
中的一个不同上下文跟踪的实体,但是由于我不想尝试将该实体分配给新创建的可计费用,所以我不会看看它是如何成为一个问题。
我能看到错误发生的唯一方法是因为分配给新Billable
一些int
值是从正由不同上下文跟踪的现有EndProduct
中获取的,但IEntityChangeTracker
肯定不会跟踪个别实体的原语?
public void AddBillable(EndProduct endProduct, int? purchaseId, string centreCode, int userId) { if (endProduct.Product != null) { var existingBillableForUserForProductId = _billableRepository.GetQuery(b => b.UserId == userId && b.ProductId == endProduct.ProductId); if (endProduct.BillablePartId != null && !existingBillableForUserForProductId.Any()) { var billable = new Billable { ProductId = endProduct.ProductId.Value, //int UserId = userId, //int PartId = endProduct.BillablePartId.Value, //int DateAdded = DateTime.UtcNow, //datetime PurchaseId = purchaseId, //int CentreCode = centreCode //string }; _billableRepository.Add(billable); //error here _billableRepository.UnitOfWork.SaveChanges(); } } }
最可能的原因是您正在使用的任何dependency injection工具。
每个工作单元应该只有一个DbContext
。 如果您每次都要新建一个新的,请确保旧的旧的处理掉。
否则,您将拥有相同上下文的多个实例并排运行。
这是变更跟踪器混淆的地方,无法跟踪您的实体的变化。
这个示例代码将解决问题;
public class DataModel { private static DBContext context; public static DBContext Context { get { if (context == null) { context = new SozlukContext(); return context; } return context; } } } public class EntryRepository : IEntryRepository { DBContext _context = DataModel.Context; public IEnumerable GetAll() { return _context.Entry.Select(x => x); } }
在你的模型(GetById method)
尝试这样的东西:
var billable = _db.Billable.
AsNoTracking()。 .SingleOrDefault(i => i.BillableId == id);
使用AsNoTracking(),以便它返回一个新的查询,其中实体将不会缓存在System.Data.Entity.DbContext
您可以通过将实体附加到存储库中来进行修复。 像这样:
_context.Set.Attach(entity)
在上下文中设置其DbSet的位置。
上述就是C#学习教程:entity framework“实体对象不能被IEntityChangeTracker的多个实例引用”分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/960950.html