2

I have two types of users: a CRM user and a system user. We have a record of every CRM user, thanks to a nightly sync that we run (so we don't have to hit the CRM API every time). We have system users that don't have CRM accounts. We also have CRM users that aren't in our system. If a system user happens to have a CRM account, we want to link the two accounts together. So, this is an optional-to-optional relationship.

Originally, I put a foreign key on the CRM user table. This was enough for us to determine if a system user was in CRM or the other way around. I could have put the foreign key on the system user table just as easily. However, there's the off chance that, in the future, we will be linking other types of accounts to our system accounts, as well. I didn't want to keep adding new null-able columns to the system user table when I could just as easily add them to new tables.

I am using Entity Framework and it seems to hate optional-to-optional relationships. The only way I have been able to configure this relationship is using a one-to-many relationship. In the system user entity, I have a collection of CRM users. This works, except the code needs to constantly say user.CRMUsers.FirstOrDefault() which makes the code awkward and hard to read. Going in the opposite direction is fine, because the CRM user just links to a single system user (or null).

This has got me thinking that maybe I am representing optional-to-optional relationships incorrectly in my database. There's no clear reason why the foreign key should be on one table or the other. Perhaps a many-to-many table with a unique constraint is better (but I think that would mean having a collection in both entities, yuck!).

So, how should I be representing these types of relationships? Will EF understand that representation?

1 Answer 1

2

You should represent them as many to many. optional to optional does not really describe the relationship of the data

Many to many does not 'require' either side to actually exist unless you enforce it through triggers, not null foreign key fields and the like.

A many to many relationship can also be thought of, and referenced as, a mapping table.

2
  • Many:Many could include 0:0 (optional-to-optional). Commented Nov 18, 2014 at 21:50
  • Am I getting old, when schoolbook give new name to same stuff? Commented Nov 19, 2014 at 7:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.