流利的API -一二多关系
本文关键字:关系 API | 更新日期: 2023-09-27 18:13:52
我有两个实体,即雇员和公司。它们都可以有一个或多个地址。由于Guid总是唯一的,所以我想在员工和公司中使用Guid作为地址中的外键。
在Address for Employee中可以有多个条目,Employee的Guid将在Guid Field 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?
}
我不确定我是否理解你的问题。你想要两个简单的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; };
}
设置你喜欢的实体
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在这里的建议去做。
modelBuilder.Entity<Company>()
.HasMany(c => c.Addresses)
.WithRequired()
.HasForeignKey(a => a.OwnerId);
modelBuilder.Entity<Employee>()
.HasMany(c => c.Addresses)
.WithRequired()
.HasForeignKey(a => a.OwnerId);