[英]How do you detach an object within a parent object in EF Core?
我有一个单元测试来测试在数据库中插入相同的 object 两次将给出ArgumentException
。 我有这个 class:
public class Foo
{
public Guid Id { get; set; }
public List<Bar> Bars { get; set; }
}
而这个单元测试:
[Fact]
public async Task AddFooAsync_ContainsExistingFoo_TrowsArgumentException()
{
// arrange
using var context = new MyDbContext(MockDbContext.CreateInMemoryContext());
var fooRepository = new FooRepository(context, cacheService, myMapper); // cacheService and myMapper are succesfully instantiated elsewhere.
// Add a Foo to the database.
var myFoo = new Foo
{
Id = Guid.Parse("abc-123"),
Bars = new List<Bar> { new Bar { Id = Guid.Parse("def-456") } }
};
_context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
_context.Foo.Add(myFoo);
_context.SaveChanges();
_context.Entry(myFoo).State = EntityState.Detached;
_context.SaveChanges();
// This is a DTO object that is almost the same as the Foo entity above. Same for the Bar List
var fooDTO = new FooDTO
{
Id = Guid.Parse("abc-123"),
Bars = new List<BarDTO> { new BarDTO { Id = Guid.Parse("def-456") } }
}
// act + assert
await Assert.ThrowsAsync<ArgumentException>(() => fooRepository.AddFooAsync(fooDTO));
}
AddFooAsync 方法如下所示:
public async Task<FooDTO> AddFooAsync(FooDTO foo)
{
// use AutoMapper to turn the Foo DTO into a Foo entity.
var dbFoo = _mapper.Map<Foo>(foo);
_dbContext.Foos.Add(dbFoo);
await _dbContext.SaveChangesAsync();
return _mapper.Map<UserDTO>(dbUser);
}
此方法在_dbContext.Foos.Add(dbFoo);
行,并抛出一个InvalidOperationException
而不是我预期的ArgumentException
。 我得到以下文字:
无法跟踪实体类型“Bar”的实例,因为已在跟踪另一个具有键值“{Id: def-456 }”的实例。 附加现有实体时,请确保仅附加一个具有给定键值的实体实例
我最好的猜测是 EF 也在跟踪 Bar object,这在进行双插入时给我带来了问题。 go 解决此问题的最佳方法是什么?
如果适合您,您可以分离所有内容:
foreach (var e in _dbContext.ChangeTracker.Entries())
{
e.State = EntityState.Detached;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.