【问题标题】:How to solve possibly one-to-one relationship issue - Entity Framework Core如何解决可能的一对一关系问题 - Entity Framework Core
【发布时间】:2021-12-16 05:36:39
【问题描述】:

我有点迷茫,这是我的业务逻辑:

当新用户被添加到系统时,它应该属于某个公司(只有一个公司),所以我的用户实体如下所示:

public class User : IdentityUser<long>
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Company Company { get; set; }
    public long? CompanyId { get; set; }
    public string ProfileImageUrl { get; set; }
}

基本上,当添加用户时,管理员可以在其中选择与该用户相关的公司,这很好。 (用户被视为该公司的员工)

但过了一段时间,我们意识到每个公司都必须有一个与该公司相关的商业家(用户)。因此,例如,如果对公司销售的产品有一些其他问题,我们应该联系的第一个人是与该公司相关的商业人士,我的公司实体如下所示:

public class Company : BaseEntity<long>, IDeleted
{
    public string Title { get; set; }
    public string Description { get; set; }
    public long? CommercialistId { get; set; }
    public User Commercialist { get; set; }
}

现在我在这里遇到了一个问题,因为我无法添加两个具有相同业务员的公司。例如,商业家约翰正在报道两家公司,苹果和三星。 但在这种情况下,我似乎已经建立了一对一的关系,而 John 只能涵盖其中一家公司。

我该如何解决这个问题,以便将 John 与他支持的两家或更多公司联系起来? (不添加额外的表格?)

谢谢大家!

干杯!

【问题讨论】:

  • 面向未来的自己:添加一个 CompanyUser 表,该表有一个 UserId、一个 CompanyId,可能还有一个“角色”(可能是“commercialist”和“user”?)
  • 将关系配置为两个一对多关系。
  • 到目前为止,对我来说一切正常。主要问题是一家公司能否拥有 2 名或更多商业人士?
  • @Serge 一家公司一次只能有一名活跃的商业人士,因此答案是:公司只有一名商业人士。
  • @GertArnold 我该怎么做?例如,通过添加额外的表 CompanyCommercialist ?

标签: c# .net-core entity-framework-core linq-to-entities


【解决方案1】:

最简单的方法是将 IsCommercialist 标志添加到 User 类。

public class User : IdentityUser<long>
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public bool IsCommercialist {get; set;}

    public long? CompanyId { get; set; }

    [ForeignKey(nameof(CompanyId))]
    [InverseProperty("Users")]
    public Company Company { get; set; }
  
    [InverseProperty(nameof(Company.Commercialist))]
    public virtual ICollection<Company> CommercialistCompanies {get; set;}

    public string ProfileImageUrl { get; set; }
}

public class Company : BaseEntity<long>, IDeleted
{
    public string Title { get; set; }
    public string Description { get; set; }

    public long? CommercialistId { get; set; }

    [ForeignKey(nameof(CommercialistId ))]
    [InverseProperty("CommercialistCompanies")]
    public User Commercialist { get; set; }

    [InverseProperty(nameof(User.Company)]
    public virtual ICollection<User> Users {get; set;}
}

但我担心必须像我一样手动定义关系,因为 EF 无法正确完成

【讨论】:

    猜你喜欢
    • 2017-02-17
    • 2019-08-07
    • 2020-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多