I am using EF5 with a Code First and Fluent Mapping Approach. Here's my scenario, trimmed down for clarity:
public class SecuritySettings
{
public int Id { set; set }
public Company Company { get; set; }
public int MaximumInvalidPasswordAttempts { get; set;
// etc.
}
public class Company
{
public int Id { set; set }
public string Name { get; set; }
public SecuritySettings InternalUserSecuritySettings { get; set; }
public SecuritySettings ExternalUserSecuritySettings { get; set; }
}
With just the above, I get two FKs in the Company table:
InternalUserSecuritySettings_Id int, null
ExternalUserSecuritySettings_Id int, null
So far, so good.
I have configuration classes I used to set out my fluent mapping - one for Company and one for SecuritySettings. These are stipulating required properties. Within the Company configuration, if I do the following:
HasRequired(x => x.InternalUserSecurityConfiguration);
This results in:
InternalUserSecuritySettings_Id int, not null ExternalUserSecuritySettings_Id int, null
BUT, if I then add this:
HasRequired(x => x.ExternalUserSecurityConfiguration);
I get the following exception:
Introducing FOREIGN KEY constraint 'FK_dbo.Companies_dbo.SecuritySettings_ExternalUserSecurityConfiguration_Id' on table 'Companies' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
I have tried:
- .WithRequiredDependent(y => y.Company).WillCascadeOnDelete(false)
- .WithRequiredDependent(y => y.Company).Map(m => m.MapKey("ExternalUSC_Id"))
Amongst other such permutations but either I get an exception or only one of the FKs get created. I would like to do this within the Fluent Mapping of the entity configuration - preferably the Company one. Am I missing something obvious. It seems such a shame that going from something so easy and trivial with the not nulls to finding it so hard to simply stipulate I want a key for each and both must not be null quite frustrating.
I did find a way to get this to work by using a separate property for the actual Foreign Key but firstly, this seems such an extra effort for a not null requirement and secondly, I had to declare a lot of configuration in the OnModelCreating method using a "WithMany()" mapping which is just counter-intuitive to me!