简体   繁体   English

与单表实体框架asp.net MVC的多个关系

[英]Multiple relationships to single table Entity Framework asp.net MVC

I've just started using Entity Framework for my next project and I'm struggling with the following. 我刚刚开始为我的下一个项目使用Entity Framework,我正在努力解决以下问题。 I have the following ApplicationUser class: 我有以下ApplicationUser类:

public class ApplicationUser : IdentityUser 
{
    public string Name { get; set; }
    public int CompanyId { get; set; }
    public virtual Company Company { get; set; }
}

I have two classes that inherent from this class: 我有两个这个类固有的类:

public class TrainerUser : ApplicationUser  
{
    public virtual ICollection<ClientUser> Clients { get; set; }
}

public class ClientUser : ApplicationUser 
{
    public string TrainerId { get; set; }
    public TrainerUser Trainer { get; set; }
}

The company class looks like this: 公司类看起来像这样:

public class Company 
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<TrainerUser> Trainers { get; set; }
    public virtual ICollection<ClientUser> Clients { get; set; }
}

What I can't figure out is how I can use the fluent API to not include 3 different companyId columns in the ApplicationUsers table. 我无法弄清楚我是如何使用流畅的API在ApplicationUsers表中不包含3个不同的companyId列。

Currently I have the following fluent API configuration: 目前我有以下流畅的API配置:

modelBuilder.Entity<TrainerUser>().HasRequired(c => c.Company).WithMany(t => t.Trainers).HasForeignKey(c => c.CompanyId);
modelBuilder.Entity<ClientUser>().HasRequired(c => c.Company).WithMany(c => c.Clients).HasForeignKey(c => c.CompanyId);

Can anyone point me in the right direction? 谁能指出我正确的方向?

Try adding these to your code. 尝试将这些添加到您的代码中。

modelBuilder.Entity<TrainerUser>().ToTable("TrainerUser");
modelBuilder.Entity<ClientUser>().ToTable("ClientUser");

If I am getting you right. 如果我找对你 you are trying to create a structure representing Table Per Hierarchy (TPT) . 您正在尝试创建表示每个层次结构(TPT)的结构 Read more about it at the link. 在链接上阅读更多相关信息。

Basically what happens is when entity framework encounters inheritance in the entities. 基本上,当实体框架在实体中遇到继承时会发生什么。 Its Default attempt to create tables is by creating column of the set of all properties of all the derived entities from a class with a discriminator column. 它默认尝试创建表是通过使用discriminator列创建所有派生实体的所有属性集的列。

What you are trying to create is a separate table for every class in the hierarchy. 您要创建的是层次结构中每个类的单独表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM