public class Test : FullAuditedAggregateRootWithUser<Guid, AppUser> { public string TransactionNumber { get; set; } public virtual List<TestItem> TestItems { get; set; } } public class TestItem : AuditedEntity { public Guid TestId { get; set; } public Guid ItemId { get; set; } [ForeignKey("ItemId")] public Item Item { get; set; } public int Quantity { get; set; } public virtual List<TestSubItem> TestSubItems { get; set; } public override object[] GetKeys() { return new object[] { TestId,ItemId }; } } public class TestSubItem : AuditedEntity { public Guid TestId { get; set; } public Guid ItemId { get; set; } [ForeignKey("TierId")] public Tier Tier { get; set; } public Guid TierId { get; set; } public int Quantity { get; set; } public override object[] GetKeys() { return new object[] { TestId, ItemId , TierId }; } }
当update TestItem的值 , 使用updateaync会报错
2021-03-27 18:51:43.422 +08:00 [ERR] The instance of entity type ‘TestSubItem‘ cannot be tracked because another instance with the same key value for {‘TestId‘, ‘ItemId‘, ‘SubItemId‘} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using ‘DbContextOptionsBuilder.EnableSensitiveDataLogging‘ to see the conflicting key values.
研究了好久,找不到方法override 这个类 StateManager.
用下面改变 EntityState 的方法是有时凑效有时不凑效
_context.Attach(modelPostedToController); IEnumerable<EntityEntry> unchangedEntities = _context.ChangeTracker.Entries().Where(x => x.State == EntityState.Unchanged); foreach(EntityEntry ee in unchangedEntities){ ee.State = EntityState.Modified; } await _context.SaveChangesAsync();
最后的解决方案是先 remove 再 update, 而且一定不能用 DbContext.SaveChangesAsync()
要是用aynchu会报错
[ERR] A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913.
public class TestItemRepository : EfCoreRepository<DRSDbContext, TestItem>, ITestItemRepository { public TestItemRepository(IDbContextProvider<DRSDbContext> dbContextProvider) : base(dbContextProvider) { } public Task Save(List<TestItem> entities) { DbContext.AttachRange(entities); DbContext.UpdateRange(entities); DbContext.SaveChanges(); return Task.CompletedTask; } public Task Remove(List<TestItem> entities) { DbContext.AttachRange(entities); DbContext.RemoveRange(entities); DbContext.SaveChanges(); return Task.CompletedTask; } }
ABP框架使用(版本3.3.1) - EntityFramework
原文:https://www.cnblogs.com/sui84/p/14587405.html