I have to store some emergency information to a membership and I struggle with how to design the SQL tables. I found this very useful old question but I’m still struggling with the answer.
I noticed that an emergency contact will have the same information as a standard user. Then I would like to reuse the same structure as I already have to do so. Let’s me show you what I have so far (I use code first, C# and I simplified the model for demonstration purpose):
Membership table
public class Membership
{
public string Id { get; set; }
public tring PhoneNumber { get; set; }
public tring UserName { get; set; }
public tring Email { get; set; }
public bool IsDeactivated { get; set; }
public bool IsAccountClosed { get; set; }
/// <summary>
/// In some cases like teammate, a membership can be linked to another membership. We'll be able to build teammate and other scenario.
/// </summary>
public string MembershipGroupId { get; set; }
public int DisplayOrder { get; set; }
public virtual UserProfile UserProfile { get; set; }
/// <summary>
/// The most of the time, a membership will have some emergency contacts
/// </summary>
public virtual ICollection<EmergencyContact> EmergencyContacts { get; set; }
}
}
If an emergency contact can be linked to many membership and a membership can have many emergency contact, then I should create a many to many relationships.
EmergencyContact
public class EmergencyContact : Entity
{
public string MembershipId { get; set; }
public string MembershipEmergencyId { get; set; }
public virtual Membership Membership { get; set; }
public virtual Membership MembershipEmergency { get; set; }
}
And I defined the FluentAPI like below:
modelBuilder.Entity<EmergencyContact>()
.HasKey(x => new { x.MembershipId, x.MembershipEmergencyId });
// EmergencyMembership to Membership
modelBuilder.Entity<EmergencyContact>()
.HasRequired(x => x.Membership)
.WithMany(x => x.EmergencyContacts)
.HasForeignKey(x => x.MembershipId);
// EmergencyMembership to MembershipEmergencyId
modelBuilder.Entity<EmergencyContact>()
.HasRequired(x => x.MembershipEmergency)
.WithMany(x => x.EmergencyContacts)
.HasForeignKey(x => x.MembershipEmergencyId);
And finally, I got this error Schema specified is not valid. Errors: The relationship EmergencyContact_Membership' was not loaded because the type Membership' is not available.
As you can see, EmergencyContact refers to membership twice because I expect that an emergency contact will have a standard membership as any other users. FluentAPI seams to not like that, I need some help to make this to work.
Thank you very much,
David