I have the following (simplified) classes:
public class Person
{
public string Id {get; set;} //Ignore the fact that the Id is string -- legacy system
public string Firstname {get; set;}
public ICollection<Member> Memberships {get; set;}
...
}
public class Account
{
public string Id {get; set;}
public string AccountType {get; set;}
...
}
public class Member
{
public string AccountNumber {get; set;}
public string PersonNumber {get; set;}
public Account Account {get; set;}
public Person Person {get; set;}
...
}
and the following EF configuration:
//In Accounts configuration class
ToTable("missacct");
HasKey(a => a.Id);
//In Members Configuration class
ToTable("members");
HasKey(a => new { a.AccountNumber, a.PersonNumber});
HasRequired(a => a.Person).WithMany().HasForeignKey(p => p.PersonNumber);
HasRequired(a => a.Account).WithMany().HasForeignKey(a => a.AccountNumber);
//In Persons Configuration Class
ToTable("person");
HasKey(p => p.Id);
HasMany(p => p.Memberships).WithOptional().HasForeignKey(p => p.PersonNumber);
The intent here is that there are persons and accounts. An account can not exist without members and a member is always a person. But, a person can exist without being a member of an account.
The idea is I want to be able to query the following:
- Given a specific account number I want to find all the people on the account.
- Given a first/last name combination I want to find all persons with matching names and any accounts that they may be members of.
What I have does not currently seem to work. I’m getting a circular reference error but I’m not quite sure where I’ve gone wrong.
Thanks for any help you can offer!
You are defining two separate relationships instead of one bidirectional relationship. Try this:
You will have to enforce this part in your application logic. At relationship level you can only say that a member must have an account.