I am trying to configure a One-To-Many relationship where the second table has a reference to the first table. The tables are in an existing legacy Sql Server database.
I have a Customer table and a CustomerBranches table like so:
I have a POCO that will allow a Customer object to navigate to its BranchCustomers (Children) if it has any, and also to navigate to its ParentCustomer (Parent) if itself is a Child.
public class Customer
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public virtual List<Customer> BranchCustomers { get; set; }
public virtual Customer ParentCustomer { get; set; }
}
I can't get this to work with data annotations or with the Fluent API.
The only way I can get the relationship to "sort" of work in EF is to use a many-to-many relationship using the Fluent API:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>()
.HasMany<Customer>(s => s.BranchCustomers)
.WithRequired(c => c.ParentCustomers)
.Map(cs =>
{
cs.MapLeftKey("ParentCustId");
cs.MapRightKey("ChildCustId");
cs.ToTable("CustomerBranches");
});
}
and the POCO to:
public class Customer
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public virtual List<Customer> BranchCustomers { get; set; }
public virtual List<Customer> ParentCustomers { get; set; }
}
In this case, when the Customer is a child, the ParentCustomers collection will only have One customer. It's a kludge, I know. What is the appropriate approach in this situation?
Thank you.