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

时间:2016-12-05 11:36:17

标签: 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”(因为它没有添加到灯具中)但是当我尝试添加“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);
        }
    }
}

1 个答案:

答案 0 :(得分:2)

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

Some information about collection 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