【问题标题】:Add TPT Inherited Code First Model to Linq Fluent API将 TPT 继承的代码优先模型添加到 Linq Fluent API
【发布时间】:2017-08-23 23:05:28
【问题描述】:

我在将 Fluent API 扩展到我的继承类时遇到问题。我采用了 TPT(每种类型的表)方法,并且每种类型的继承都有一个表。我喜欢每种类型的表,因为数据库已完全规范化且易于维护。我没有让继承模型 ServiceCompany 与 Fluent API 一起使用。

基础抽象类

public abstract class Vendor
{
    [Key]
    public int VendorID { get; set; }

    [Required]
    public string CompanyName { get; set; }

    [Required]
    public int StreetNumber { get; set; }

    [Required]
    public string StreetName { get; set; }
}

从供应商继承的 ServiceCompany 类

[Table("ServiceCompanies")]
public class ServiceCompany : Vendor
{
    public string ACHClaim { get; set; }

    public virtual ICollection<SubContractorCompany> SubContractorCompanies { get; set; }

    public virtual ICollection<ServiceCompanyUser> SubContractorUsers { get; set; }
}

我添加了实体模型以使用 onModelCreating() 启用 Fluent API

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
     public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
    }

    public DbSet<Vendor> Vendors { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<ServiceCompany>().ToTable("ServiceCompanies");
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
}

我希望能够使用 fluent API 做这样的事情。

var ListofServiceCompanies = db.ServiceCompanies.All()

不是这样的

var ListofServiceCompanies = db.Vendor.SelectMany( Vendor is a ServiceComapny...etc)

我更喜欢正确设置实体并使代码美观且易于使用。感谢任何见解或知识。

【问题讨论】:

    标签: entity-framework linq inheritance linq-to-entities


    【解决方案1】:

    您可以通过调用OfType 扩展方法来做到这一点,如下所示:

    var ListofServiceCompanies = db.Vendor.OfType<Vendor>().ToList();
    

    或者你可以在你的DbContext 中添加一个DbSet&lt;ServiceCompany&gt; ServiceCompanies { get; set; },所以它看起来像这样:

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
         public ApplicationDbContext()
            : base("DefaultConnection", throwIfV1Schema: false)
        {
        }
    
        public DbSet<Vendor> Vendors { get; set; }
    
        public DbSet<ServiceCompany> ServiceCompanies { get; set; }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<ServiceCompany>().ToTable("ServiceCompanies");
        }
    
        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }
    }
    

    然后只需调用:

    var ListofServiceCompanies = db.ServiceCompanies.ToList();
    

    【讨论】:

    • 为 TPT(每种类型的表)继承设置 Fluent API 的精彩解释
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多