Свободный API - One 2 Many Relationship
У меня есть две организации: сотрудник и компания. Оба из них могут иметь один или несколько адресов. Поскольку Guid всегда уникален, поэтому я хочу использовать Guid в Employee и Company в качестве внешнего ключа в Address.
Это может быть несколько записей в Address for Employee, и Guid of Employee будет в поле адреса Guid.
Точно так же, для компании может быть несколько адресов. И Guid of Company будет в Guid of Address.
Не могли бы вы помочь мне настроить отношения между сотрудником и адресом компании с помощью Fluent API?
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 ответа
Я не уверен, понял ли я вашу проблему. Вы хотите два простых отношения 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
}
затем в свободном 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);