繁体   English   中英

如何在实体框架类中引用两个用户(每个用户具有不同的角色)

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

我在AspNetUsers表中有一个与两个用户有关的实体:

  1. 具有租户角色的用户
  2. 具有房东角色的用户
  3. 属性(使用实体框架创建)

在我的财产环境中创建外键关系时,我不知道如何将1个租户和1个房东与1个财产联系起来。 为此,我需要在我的属性类中实现两个外键,但它们都是Identity的UserID。 但这似乎并不正确,我也无法解决。 下面是Property.cs文件开头的样子。

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; }
}

您有两种方法可以做到这一点:

  1. 保留当前模型,并确保正确设置导航属性:

     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; } } 

    请注意,由于这正确地遵循了配置约定,因此不需要应用[ForeingKey]

  2. 这将代表您的应用程序中的更大变化。 您需要引入LandlordTenant实体:

     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 } } 

    然后将它们映射到Property实体:

     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; } } 

现在,哪种方法在您的业务领域和本应用程序中更有意义,由您决定。

暂无
暂无

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

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