2016-10-20 8 views
1

У меня есть две компании, а именно сотрудники и компания. Оба они могут иметь один или несколько адресов. Поскольку Guid всегда уникален, поэтому я хочу использовать Guid in Employee и Company в качестве внешнего ключа в адресе.
Это может быть несколько записей в адресе для сотрудника, а руководство сотрудника будет в поле «Адрес направления».
Точно так же может быть несколько адресов для компании. И руководство компании будет в «Руководстве по обращению».Fluent API - One 2 Many Relationship

Можете ли вы помочь мне, как настроить отношения/б Служащий-адрес и компании-адрес с помощью 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; }; 
} 
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); 

 Смежные вопросы

  • Нет связанных вопросов^_^