简体   繁体   English

实体框架每个类型的表:1:0…*与派生类的FK关系-是基类还是派生类的FK?

[英]Entity Framework table-per-type: 1:0…* FK relationship with a derived class - is FK of base class or derived class?

I have a class Tenant which is of the abstract type UserProfile . 我有一个Tenant类,它是抽象类型UserProfile I'm using the table-per-type inheritance approach. 我正在使用每个类型的表继承方法。 A tenant can represent a group of tenants. 租户可以代表一组租户。 A TenantGroupMember is one of such a group. TenantGroupMember是此类组之一。 So, 1 Tenant can have zero or many TenantGroupMember s. 因此,1个Tenant可以具有零个或多个TenantGroupMember

How is this association represented using the table-per-type approach? 如何使用每个类型的表格表示这种关联? They way I've approached it is as follows: 我所采用的方式如下:

[Table("TenantGroupMember")]
public class TenantGroupMember
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int TenantGroupMemberId { get; set; }

    // 1:many with Tenant - base UserProfile
    public int UserProfileId { get; set; }
}

[Table("Tenant")]
public class Tenant : UserProfile
{
    public string TenantAge { get; set; }
    public string PersonalDescription { get; set; }

    // 1:many with TenantGroupMember
    public virtual ICollection<TenantGroupMember> TenantGroupMembers { get; set; }
}

Am I correct in making the FK in TenantGroupMember from UserProfile ? 我是否TenantGroupMember通过UserProfileTenantGroupMember中创建FK吗? Because of the ICollection TenantGroupMembers is in Tenant , will EF know that a TenantGroupMember can only be associated with a Tenant , and any not any other derived classes of UserProfile ? 由于ICollection TenantGroupMembers位于Tenant ,EF是否会知道TenantGroupMember只能与Tenant相关联,而不能与UserProfile任何其他派生类关联?

Yes, you are right. 是的,你是对的。 However, you have to explicitly declare the TenantGroupMember.UserProfileId property as foreign key of the relationship. 但是,您必须显式声明TenantGroupMember.UserProfileId属性为关系的外键。 EF won't detect this by convention and would treat it as ordinary scalar property and create another FK column in the database. EF不会按惯例检测到此错误,而是将其视为普通标量属性,并在数据库中创建另一个FK列。 You can do it with data annotations... 您可以使用数据批注...

[ForeignKey("UserProfileId")]
public virtual ICollection<TenantGroupMember> TenantGroupMembers { get; set; }

...or with Fluent API: ...或使用Fluent API:

modelBuilder.Entity<Tenant>()
    .HasMany(t => t.TenantGroupMembers)
    .WithRequired()
    .HasForeignKey(tgm => tgm.UserProfileId);

The relationship will have the Tenant table in the database as principal/primary key table, not the UserProfile table. 该关系会将数据库中的“ Tenant表作为主/主键表,而不是UserProfile表。

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

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