如何确定 Child 或 GrandChild Class 是否需要 TenantId?

How Do I Determine if a Child or GrandChild Class Needs a TenantId?

假设您有一个租户,该租户有很多用户,这些用户有很多账户,有很多交易。

您将 TenantId 添加到树下多远 属性?
您将 UserId 添加到树下多远的位置?
还是您只需要 parent ID?

假设用户永远不会故意访问 child 实体而不首先访问它的 parent。在 slug 中,它会是这样的: baseurl.com/accounts/{accountId/transactions/{transactionId}

public class Tenant
{
    public long Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<User> Users { get; set; }
    public virtual ICollection<Account> Accounts { get; set; }
    public virtual ICollection<Transaction> Transactions { get; set; }
}

public class User
{
    public long Id { get; set; }
    public long TenantId { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Account> Accounts { get; set; }
}

public class Account
{
    public long Id { get; set; }
    public long TenantId { get; set; }
    public string UserId { get; set; }
    public virtual ICollection<Transaction> Transactions { get; set; }
}

public class Transaction
{
    public long Id { get; set; }
    public long TenantId { get; set; }
    public string UserId { get; set; }
    public string AccountId { get; set; }
}

我倾向于看到在属于租户的所有内容上使用 TenantId 的示例。我想这是为了安全,但我的自然假设是 UserId 就足够了。例如,即使交易低于用户两级,我认为我不应该允许任何知道交易 ID 的人访问交易而不是拥有该帐户的用户。

我们为所有主要实体添加 TenantId 所遵循的规范。例如,用户和帐户应具有 TenantId。由于交易是用户和账户的依赖实体,因此如果不引用基础(账户/用户)就无法获取它,因此 没有授权 对于 TenantId。

经验法则是对要由租户分组/分类的主要业务实体进行分类。 (用户、帐户等)以便在数据库中检索或更新数据时,在对映射表或子表执行任何操作之前进行适当的租户过滤。因此,请根据域对象明智地包含 TenantId 列。