【问题标题】:How to reference two users(each with a different role) in an Entity Framework Class如何在实体框架类中引用两个用户(每个用户具有不同的角色)
【发布时间】:2018-03-08 07:38:18
【问题描述】:

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

【问题讨论】:

  • @CamiloTerevinto 刚刚做了一些编辑。希望他们使问题更清楚。谢谢!

标签: c# entity-framework asp.net-identity


【解决方案1】:

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

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

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

【讨论】:

  • “public User Tenant { get; set; }”是否会在我的 AspNetUsers 表中获取我的 AspNetRoles 表中角色名称为“Tenant”的用户的用户 ID?
  • 不是自动的,不是。在这两种情况下,您都需要手动编写该逻辑
  • 这就是我正在努力解决的问题...我最初创建了一个房东和租户实体,但读到用角色和声明来区分用户是最佳实践。不过还是谢谢你!
  • @Luke 那里没有最佳实践,这完全取决于您的业务。不过更容易看出Landord 是否是另一个实体
猜你喜欢
  • 2012-09-02
  • 1970-01-01
  • 2015-11-02
  • 1970-01-01
  • 2015-01-02
  • 2013-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多