流畅的API - 一个2多种关系

时间:2016-10-20 11:09:42

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

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

您能否帮助我如何使用Fluent API配置关系b / w 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?


}

2 个答案:

答案 0 :(得分:2)

我不确定我是否理解你的问题。你想要这两个简单的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; };
}

答案 1 :(得分:1)

设置像

这样的实体
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


}

然后在流畅的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);