I have a class Tenant which is of the abstract type 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. So, 1 Tenant can have zero or many TenantGroupMembers.
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? 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?
Yes, you are right. However, you have to explicitly declare the
TenantGroupMember.UserProfileIdproperty as foreign key of the relationship. EF won’t detect this by convention and would treat it as ordinary scalar property and create another FK column in the database. You can do it with data annotations……or with Fluent API:
The relationship will have the
Tenanttable in the database as principal/primary key table, not theUserProfiletable.