0

I want to share Contacts entity between my Customers and Vendors.

Customers can have many Contacts

Vendors can have many Contacts

...but when I made my model I ran into a problem where now I have to supply both CustomerId and VendorId to each contact.

I'd post image of my model, but I don't have 10 points yet.

user3928549
  • 5
  • 1
  • 4

2 Answers2

0

If you are dealing with Many to Many relationships, you most likely have to use a junction table.

That means having two additional tables with two columns each:

  • VendorsContacts with primary Keys :: VendorID, ContactID
  • CustomersContacts with primary Keys :: CustomerID, ContactID

The primary keys of those tables needs to be compound, i.e both keys together serve as a single primary key. In SQL Server that is achieved by marking both columns with CTRL and creating your primary key. You'll notice both of them being marked as primary.

EntityFramework won't be creating entity classes for the junction table, you will directly get access to the Contacts of a given Customer/Vendor through yourCustomer.Contacts and similarly yourVendor.Contacts.

0

Customers can have many Contacts

Vendors can have many Contacts

As you said Can and not Has seems that the relation between Customers and Contacts and between Contacts and Vendors are zero or one to many.

So you could put CustomerId and VendorId nullable:

public class Contact
{
   public int Id { get; set;}
   public int? CustomerId {get; set;} 
   public int? VendorId {get; set;} 
   // other properties
}

public class Customer
{
   public int Id { get; set;}
   public ICollection<Contact> Contacts {get; set;}
   //other properties 
}

public class Vendor
{
   public int Id { get; set;}
   public ICollection<Contact> Contacts {get; set;}
   //other properties 
}
Masoud
  • 8,020
  • 12
  • 62
  • 123
  • I'm using model-first. I do have set nullable to true on both properties. I changed to 0/1(Customer/Vendor)-many(Contact). When I tested database first, EF set nullable property to NONE. It works now and there are no errors, but I wonder if this is normal sharing `contacts` like this between tables or if there is more "standard" way of doing it. – user3928549 Sep 21 '14 at 05:41
  • In your project, can several customers or vendors have a given contact? Because with this structure, you cannot have the same contact linked to several customers or vendors. –  Sep 21 '14 at 05:47
  • No, I don't think it would make sense if contact is shared by both customer and vendor - should i reconsider this? – user3928549 Sep 21 '14 at 05:50