Search code examples
c#entity-framework-6ef-model-first

How to map foreign keys in two entities referencing each other


I have an error here and can't quite get the logic behind it. I am using Entity Framework 6 with a model-first approach. I have designed two tables that reference each other like this:

enter image description here

Basically, an account needs to be in a company while a company has to have an account as an administrator. However, I get an error from the EF validator:

Error 3014: Problem in mapping fragments starting at lines 224, 249:The foreign key 'Foreign key constraint 'CompaniesAccounts1' from table CompaniesSet (Id) to table AccountsSet (Id):' is not being enforced in the model. An Association or inheritance relationship needs to be created to enforce this constraint.

CompaniesAccounts1 is the first association (1...*) you see here, Accounts being the principal. The second association has Companies as principal. Anybody know why I am getting this error?

All 4 properties are non-nullable Int32 types.


Solution

  • Due to AgapwIesu's comment, I came up with the following solution:

    enter image description here

    Strange thing is, and I noticed because I already tried it like this and still got the error above. After digging through the xml files of the entity model, I found a few old references that I didn't use anymore. So they messed with my existing model. After deleting those and the generated files/database script and rebuilding everything, it worked.