【问题标题】:Fluent API - One 2 Many RelationshipFluent API - 一对多关系
【发布时间】:2016-10-20 11:09:42
【问题描述】:

我有两个实体,即员工和公司。这两者都可以有一个或多个地址。 由于 Guid 始终是唯一的,所以我想在 Employee 和 Company 中使用 Guid 作为 Address 中的外键。
也就是说,员工的地址中可以有多个条目,员工的 Guid 将在地址的 Guid 字段中。
同样,一家公司也可以有多个地址。公司的 Guid 将在地址的 Guid 中。

您能帮我如何使用 Fluent API 配置黑白 Employee-Address 和 Company-Address 关系

public class Employee
{
    public int EmployeeId;
    public Guid Guid;
    .
    .
    .
    public ICollection<Address> Addresses;
}

public class Company
{
    public int CompanyId;
    public Guid Guid;
    .
    .
    .
    public ICollection<Address> Addresses;
}

public class Address
{
    public int AddressId
    public Guid Guid; // Guid from Employee or Company
    .
    .
    . // Should here be Navigation to Employee/Company as well?


}

【问题讨论】:

    标签: c# entity-framework ef-fluent-api


    【解决方案1】:

    我不确定我是否理解您的问题。你想要这样两个简单的 1:N 关系吗?:

    Emplyee 1:N Adress
    Company 1:N Adress
    

    如果是这种情况,你应该有这个模型:

    public class Employee
    {
        public int EmployeeId { get; set; };
        // ...
        public virutal ICollection<Address> Addresses { get; set; };
    }
    
    public class Company
    {
        public int CompanyId { get; set; };
        // ...
        public ICollection<Address> Addresses { get; set; };
    }
    
    public class Address
    {
        public int AddressId { get; set; };
        public int? EmployeeId { get; set; };
        public int? CompanyId { get; set; };
        // ...
        public virtual Employee Employee { get; set; };
        public virtual Company Company { get; set; };
    }
    

    【讨论】:

      【解决方案2】:

      设置您的实体,例如

      public class Employee
      {
          //no need of following line. just use the GUID as Employee id
          //public int EmployeeId;  
          public Guid EmployeeId;
          .
          .
          .
          public ICollection<Address> Addresses;
      }
      
      public class Company
      {
          public int CompanyId;//no need of this line, use guid as company id
          public Guid CompanyId;
          .
          .
          .
          public ICollection<Address> Addresses;
      }
      
      public class Address
      {
          public int AddressId
          public Guid OwnerId; // Guid from Employee or Company
          .
          .
          //don't add Navigation to Employee/Company
      
      
      }
      

      然后在 fluent API 中,执行slauma 建议here 的操作。

      modelBuilder.Entity<Company>()
      .HasMany(c => c.Addresses)
      .WithRequired()
      .HasForeignKey(a => a.OwnerId);
      
      modelBuilder.Entity<Employee>()
      .HasMany(c => c.Addresses)
      .WithRequired()
      .HasForeignKey(a => a.OwnerId);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-03
        • 2019-01-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多