Reputation: 341
I have two Entities i.e. Employee and Company. Both of these can have one or many addresses. As Guid is always unique, so i want to use Guid in Employee and Company as a foreign key in Address.
That's there can be multiple entries in Address for Employee and Guid of Employee will be in Guid Field of Address.
In the same way, There can be multiple addresses for a company as well. And Guid of Company will be in Guid of Address.
Can you please help me how to configure relationship b/w Employee-Address and Company-Address using Fluent APIs
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?
}
Upvotes: 1
Views: 166
Reputation: 11
Setup you entities like
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
}
then in fluent API, do what slauma has suggested 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);
Upvotes: 1
Reputation: 1034
I'm not sure If I've understood your problem. Do you want two simple 1:N relations like these?:
Emplyee 1:N Adress
Company 1:N Adress
If this is the case, you should have this model:
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; };
}
Upvotes: 2