如何使用Microsoft.EntityFrameworkCore.InMemory将共享同一数据库的不同DbContext中的不同实体映射到同一表?

时间:2019-02-11 16:03:40

标签: c# .net unit-testing entity-framework-core

我有两个不同实体类型(!)的不同DbContext,它们共享同一数据库。我想通过Microsoft.EntityFrameworkCore.InMemory在内存中使用DbContext。问题:我无法映射 Context2的Entity2到存储Context1的Entity1的同一表。如果我使用相同的实体,那么它适用于不同的实体。

using System.Linq;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;

using Xunit;

namespace EntityFrameworkCoreLabs
{
    public class Context1 : DbContext
    {
        public Context1(DbContextOptions options) : base(options)
        {
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Entity1>().ToTable("SharedEntities");
        }
    }

    public class Context2 : DbContext
    {
        public Context2(DbContextOptions options) : base(options)
        {
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            // Map to same table as in Context1
            modelBuilder.Entity<Entity2>().ToTable("SharedEntities");
        }
    }

    /// <summary>
    /// Entity from Context1 mapped to table "SharedEntities"
    /// </summary>
    public class Entity1
    {
        public int Id { get; set; }
    }

    /// <summary>
    /// Entity from Context2 mapped to table "SharedEntities"
    /// </summary>
    public class Entity2
    {
        public int Id { get; set; }

        public string Name { get; set; }
    }

    public class InMemoryTest
    {
        public static InMemoryDatabaseRoot DatabaseRoot = new InMemoryDatabaseRoot();

        [Fact]
        public void ShareDifferentContexts()
        {
            var options = new DbContextOptionsBuilder()
                .UseInMemoryDatabase("Shared", DatabaseRoot)
                .Options;

            using (var context1 = new Context1(options))
            {
                // Step 1: add Entity1 to table "SharedEntities"
                context1.Set<Entity1>().Add(new Entity1());
                context1.SaveChanges();
            }

            using (var context2 = new Context2(options))
            {
                // Step 1: get Entity2 from table "SharedEntities"
                // Failure Expected: 1 Actual: 0
                Assert.NotNull(context2.Set<Entity2>().FirstOrDefault());
            }
        }
    }
}

0 个答案:

没有答案