I'm trying to create a data model of companies with relations to the same type in Entity Framework code first. I want to create the relation one-way, so when a company adds another as its customer, the other company doesn't get that company as a supplier automatically.
public class Company {
[Key]
public string Id { set; get; }
public string Name { set; get; }
public virtual ICollection<Company> Customers { set; get; }
public virtual ICollection<Company> Suppliers { set; get; }
}
When I update the database like this, I end up with one connection table called "CompanyCompanies".
CompanyCompanies
| Company_Id | Company_Id1 |
|------------|-------------|
| 1234 | 1234 |
I want to create two tables to connect these values, like this:
CompanyCustomers
| Company_Id | Customer_Id |
|------------|-------------|
| 1234 | 1234 |
CompanySuppliers
| Company_Id | Supplier_Id |
|------------|-------------|
| 1234 | 1234 |
I've looked a lot at the fluent api and tried to define the relations there, but I can't seem to get my head around how to do this. I have found a lot of examples using different entities, but only this answer with relations to itself. However, when I implement the solution from that question and update the database I get an error saying that the connection timed out.
modelBuilder.Entity<Company>()
.HasMany(c => c.Customers)
.WithMany()
.Map(m =>
{
m.ToTable("CompanyCustomer");
m.MapLeftKey("CompanyId");
m.MapRightKey("CustomerId");
});
Error Number:-2,State:0,Class:11 Execution Timeout Expired.
The timeout period elapsed prior to completion of the operation or the server is not responding.
When I try with both CompanyCustomer and CompanySupplier I get antoher error
Either the parameter @objname is ambiguous or the claimed @objtype (COLUMN) is wrong.
I also tried to create a new object for the relation and having the Company object holding a list of CompanyCustomers, but when i updated the database with this I got a connection-table with three columns.
public class CompanyCustomer
{
[Key, Column(Order = 0)]
[ForeignKey("Company")]
public string CompanyId { set; get; }
[Key, Column(Order = 1)]
[ForeignKey("Customer")]
public string CustomerId { set; get; }
public virtual Company Company { set; get; }
public virtual Company Customer { set; get; }
}
CompanyCustomer
| CompanyId | CustomerID | Company_Id |
|-----------|------------|------------|
| 1234 | 1234 | 1234 |
I don't understand how i can build several relationship types between the same entity. Can I do this with the help of fluent api or do I have to re-design my model?