I need to store data in the DB that is related to two models that have a many-to-many relationship.
Each Client
can have many Contacts
and each contact can have many Clients
. Each contact has a priority at each client. I made a model with a composite key composed of a Client
ID and a Contact
ID that has a Priority
property, but it's a pain to use. For instance, I don't know a good way to order a client's contacts by priority.
So using it looks like this:
MyDbContext db = new MyDbContext();
ClientModel client = db.Clients.Find(clientId);
ContactModel contact = db.Contacts.Find(contactId);
ContactPriorityModel priorityModel = db.ContactPriorities.Find(clientId, contactId);
int priority = priorityModel.Priority;
When ContactModel
only had one related ClientModel
, ordering was as simple as client.Contacts.OrderBy(contact => contact.Priority)
, but changing this to a many-to-many relationship causes complications.
(Likely unnecessary) code:
public class MyDbContext
{
public DbSet<ClientModel> Clients { get; set; }
public DbSet<ContactModel> Contacts { get; set; }
public DbSet<ContactPriorityModel> ContactPriorities { get; set; }
}
public class ClientModel
{
public int Id { get; set; }
public virtual ICollection<ContactModel> Contacts { get; set; }
// Other properties
}
public class ContactModel
{
public string Id { get; set; }
public virtual ICollection<ClientModel> Clients { get; set; }
// Other properties
}
public class ContactPriorityModel
{
[Key, Column(Order = 0)]
public int ClientId { get; set; }
[Key, Column(Order = 1)]
public string ContactId { get; set; }
public int Priority { get; set; }
}