Search code examples
c#entity-frameworkasp.net-identity

How to reference two users(each with a different role) in an Entity Framework Class


I have one entity that relates to two users in the AspNetUsers table:

  1. User with the role of Tenant
  2. User with the role of Landlord
  3. Property (Created with entity framework)

I can't figure out how to relate 1 tenant and 1 landlord with 1 property when creating foreign key relationships in my property context. To do this I would need to implement two foreign keys in my property class but they would both be a UserID from Identity. That doesn't seem right though and I can't get my head around it. Below is what the beginning of my Property.cs file would look like.

public class Property
{
    [ScaffoldColumn(false)]
    public string PropertyID { get; set; }
    [Key, ForeignKey("User")]
    public string LandlordId { get;set; }
    [Key, ForeignKey("User")]
    public string TenantId { get;set; }

    //other fields

    public virtual ApplicationUser User { get;set; }
}

Solution

  • You have two ways to do this:

    1. Keep your current model, and ensure you set up the navigational properties correctly:

      public class Property
      {
          public int PropertyId { get; set; }
          public int TenantId { get; set; }
          public int LandlordId { get; set; }
      
          public User Tenant { get; set; }
          public User Landlord { get; set; }
      }
      

      Notice that, since this correctly follows convention over configuration, there's no need for applying [ForeingKey].

    2. This is going to represent a bigger change in your application. You would need to introduce a Landlord and a Tenant entity:

      public class Landlord
      {
          ...
          public int UserId { get; set; }
          public User User { get; set }
      }
      
      public class Tenant
      {
          ...
          public int UserId { get; set; }
          public User User { get; set }
      }
      

      And then map those to the Property entity:

      public class Property
      {
          public int PropertyId { get; set; }
          public int TenantId { get; set; }
          public int LandlordId { get; set; }
      
          public Tenant Tenant { get; set; }
          public Landlord Landlord { get; set; }
      }
      

    Now, which of those approaches make more sense in your business domain and in this application is up to you to decide.