实体框架核心1.1在内存数据库中无法添加新实体

entity-framework-core

我在测试设置的单元测试中使用以下代码:

var simpleEntity = new SimpleEntity();
var complexEntity = new ComplexEntity
{
    JoinEntity1List = new List<JoinEntity1>
    {
        new JoinEntity1
        {
            JoinEntity2List = new List<JoinEntity2>
            {
                new JoinEntity2
                {
                    SimpleEntity = simpleEntity
                }
            }
        }
    }
};
var anotherEntity = new AnotherEntity
{
    ComplexEntity = complexEntity1
};

using (var context = databaseFixture.GetContext())
{
    context.Add(anotherEntity);
    await context.SaveChangesAsync();
}

达到SaveChangesAsync时,EF会抛出ArgumentException并显示以下消息:

已添加具有相同键的项目。关键:1

我正在使用一个fixture也用于单元测试类,它使用相同类型的对象填充数据库,但是对于这个测试,我想要这个特定的设置,所以我想将这些新实体添加到内存数据库中。我已经尝试在DbSet(不是DbContext)上添加实体,并且分别添加所有三个实体都无济于事。然而,我可以单独添加“simpleEntity”(因为它没有添加到fixture中)但是当我尝试添加“complexEntity”或“anotherEntity”时,EF会抱怨。

看起来内存数据库中的EF无法在上下文的不同实例上处理多个Add。有没有解决方法或我在设置中做错了什么?

在这种情况下,databaseFixture是此类的一个实例:

namespace Test.Shared.Fixture
{
    using Data.Access;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.DependencyInjection;

    public class InMemoryDatabaseFixture : IDatabaseFixture
    {
        private readonly DbContextOptions<MyContext> contextOptions;

        public InMemoryDatabaseFixture()
        {
            var serviceProvider = new ServiceCollection()
            .AddEntityFrameworkInMemoryDatabase()
            .BuildServiceProvider();

            var builder = new DbContextOptionsBuilder<MyContext>();
            builder.UseInMemoryDatabase()
                   .UseInternalServiceProvider(serviceProvider);

            contextOptions = builder.Options;
        }

        public MyContext GetContext()
        {
            return new MyContext(contextOptions);
        }
    }
}

热门答案

您可以使用Collection Fixtures解决此问题,以便跨多个测试类共享此fixture。这样您就不会多次构建上下文,因此您不会遇到此异常:

有关收集夹具的一些信息

我自己的例子:

[CollectionDefinition("Database collection")]
public class DatabaseCollection : ICollectionFixture<DatabaseFixture>
{  }

[Collection("Database collection")]
public class GetCitiesCmdHandlerTests : IClassFixture<MapperFixture>
{
    private readonly TecCoreDbContext _context;
    private readonly IMapper _mapper;

    public GetCitiesCmdHandlerTests(DatabaseFixture dbFixture, MapperFixture mapFixture)
    {
        _context = dbFixture.Context;
        _mapper = mapFixture.Mapper;
    }

    [Theory]
    [MemberData(nameof(HandleTestData))]
    public async void Handle_ShouldReturnCountries_AccordingToRequest(
        GetCitiesCommand command,
        int expectedCount)
    {
        (...)
    }

    public static readonly IEnumerable<object[]> HandleTestData
        = new List<object[]>
        {
            (...)
        };
}

}

祝你好运,Seb



Related

许可下: CC-BY-SA with attribution
不隶属于 Stack Overflow
许可下: CC-BY-SA with attribution
不隶属于 Stack Overflow