我正在使用Entity Framework 7和代码优先的方法,并且有一个模型涉及3个级别的父子关系:


Corporationscompanies
Companies属于corporation并且具有factories
Factories属于company


由于这三个实体有很多共同点,因此它们都继承自抽象的BaseOrganization实体。

当我尝试列出所有工厂,包括其母公司,然后包括其母公司时,我有两种不同的情况:


在不将BaseOrganization包含在上下文中的情况下,代码优先创建三个表(与Table-Per-Concrete-Type或TPC模式相对应)。 Include()ThenInclude()工作正常,我可以按预期列出工厂和遍历关系。
包括BaseOrganization到上下文中,代码优先创建一个带有鉴别符字段的表(该字段对应于Per-Herarchy表或TPH模式)。 Include()ThenInclude()引发Sequence contains more than one matching element异常。


这个问题(没有继承和抽象基类模式)已在EF7 Github存储库中解决,并已得到解决(请参见https://github.com/aspnet/EntityFramework/issues/1460)。

因此,我目前不知道我的方法是否有问题,或者这显然与EF7 RC1有关?请注意,我真的更喜欢保留继承关系,以使我的SQL模型更具可读性。

以下是完整的复制代码:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using Microsoft.Data.Entity;

    namespace MultiLevelTest
    {
        // All places share name and Id
        public abstract class BaseOrganization
        {
            public int Id { get; set; }
            public string Name { get; set; }
        }

        // a corporation (eg : Airbus Group)
        public class Corporation : BaseOrganization
        {
            public virtual ICollection<Company> Companies { get; set; } = new List<Company>();
        }

        // a company (eg : Airbus, Airbus Helicopters, Arianespace)
        public class Company : BaseOrganization
        {
            public virtual Corporation Corporation { get; set; }
            public virtual ICollection<Factory> Factories { get; set; } = new List<Factory>();
        }

        // a factory of a company (Airbus Toulouse, Airbus US...)
        public class Factory : BaseOrganization
        {
            public virtual Company Company { get; set; }
        }

        // setup DbContext
        public class MyContext : DbContext
        {
            // if this line is commented, then code first creates 3 tables instead of one, and everything works fine.
            public DbSet<BaseOrganization> BaseOrganizationCollection { get; set; }
            public DbSet<Corporation> Corporations { get; set; }
            public DbSet<Company> Companies { get; set; }
            public DbSet<Factory> Factories { get; set; }

            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                optionsBuilder.UseSqlServer(
                    @"Server=(localdb)\mssqllocaldb;Database=MultiLevelTest;Trusted_Connection=True;MultipleActiveResultSets=true");
            }

            protected override void OnModelCreating(ModelBuilder modelBuilder)
            {
                base.OnModelCreating(modelBuilder);

                modelBuilder.Entity<Corporation>().HasMany(c => c.Companies).WithOne(c => c.Corporation);
                modelBuilder.Entity<Company>().HasMany(c => c.Factories).WithOne(c => c.Company);
                modelBuilder.Entity<Factory>().HasOne(f => f.Company);
            }
        }

        public class Program
        {
            public static void Main(string[] args)
            {
                using (var ctx = new MyContext())
                {
                    ctx.Database.EnsureDeleted();
                    ctx.Database.EnsureCreated();

                    // Add a corporation with companies then factories (this works fine)
                    if (!ctx.Corporations.Any()) CreateOrganizationGraph(ctx);

                    // Get all the factories without including anything (this is still working fine)
                    var simpleFactories = ctx.Factories.ToList();
                    foreach(var f in simpleFactories) Console.WriteLine(f.Name);

                    // Get all the factories including their mother company, then their mother corporation
                    var fullFactories = ctx.Factories
                        .Include(f => f.Company)
                        .ThenInclude(c => c.Corporation)
                        .ToList();
                    foreach (var f in fullFactories) Console.WriteLine($"{f.Company.Corporation.Name} > {f.Company.Name} > {f.Name}");
                }
            }

            public static void CreateOrganizationGraph(MyContext ctx)
            {
                var airbusCorp = new Corporation()
                {
                    Name = "Airbus Group",
                    Companies = new List<Company>()
                            {
                                new Company
                                {
                                    Name = "Airbus",
                                    Factories = new List<Factory>()
                                    {
                                        new Factory {Name = "Airbus Toulouse (FR)"},
                                        new Factory {Name = "Airbus Hambourg (DE)"}
                                    }
                                },
                                new Company
                                {
                                    Name = "Airbus Helicopters",
                                    Factories = new List<Factory>()
                                    {
                                        new Factory {Name = "Eurocopter Marignane (FR)"},
                                        new Factory {Name = "Eurocopter Deutschland (DE)"}
                                    }
                                }
                            }
                };

                ctx.Corporations.Add(airbusCorp);
                ctx.SaveChanges();

            }
        }
    }


您将希望包括以下NuGet软件包:

"EntityFramework.Commands": "7.0.0-rc1-final",
"EntityFramework.Core": "7.0.0-rc1-final",
"EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final"


更新

如我自己的评论所述,我的第一个解决方法是避免在DbContext中包含基本类型,以便代码优先生成具有TPC模式的架构(该错误仅在TPH策略中抛出)。

问题在于上面的示例比我的实际实现更简单,它涉及在基本类型级别定义的多对多关系。

由于EF7还不支持多对多关系,因此我们必须定义一个链接实体,它自己映射两个一对多的关系。

该映射实体是在基本类型级别上定义和使用的,代码优先仍然选择TPH策略,然后仍然抛出该错误。

换句话说,我被卡住了,否则我将不得不重复三遍逻辑,这几乎就像故意打破自己的腿一样!

最佳答案

我认为您不应该尝试使用基类。

组织,公司,工厂代表不同的对象,根据我在此处看到的内容,您正在尝试重构代码而不是抽象对象:

如果您创建一个存储作者和书籍的数据库,那么作者和书籍都将具有名称和ID,但是拥有基类有意义吗?

当然,您将节省几行代码,但是这会使您的代码可读性降低。

我认为您应该在有真正继承的情况下使用基类:

例如,您可以有一个基类Person和一个从Person类继承的ManagerEmployee类,因为雇员和经理都是人。

对我来说,您只需要删除基类即可,它应该可以按预期工作:

public class Corporation
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Company> Companies { get; set; } = new List<Company>();
}

public class Company
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Corporation Corporation { get; set; }
    public List<Factory> Factories { get; set; } = new List<Factory>();
}

public class Factory
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Company Company { get; set; }
}

public class MyContext : DbContext
{
    public DbSet<Corporation> Corporations { get; set; }
    public DbSet<Company> Companies { get; set; }
    public DbSet<Factory> Factories { get; set; }

    ...

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Corporation>().HasMany(c => c.Companies).WithOne(c => c.Corporation);
        modelBuilder.Entity<Company>().HasMany(c => c.Factories).WithOne(c => c.Company);
        modelBuilder.Entity<Factory>().HasOne(f => f.Company);
    }
}

09-27 13:23