简体   繁体   中英

How to define a complex (1 to 0|n) entity framework relationship with fluent api?

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:

  1. Given a specific account number I want to find all the people on the account.
  2. 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:

//In Accounts configuration class
ToTable("missacct");
HasKey(a => a.Id);

//In Members Configuration class
ToTable("members");
HasKey(a => new { a.AccountNumber, a.PersonNumber});
HasRequired(m => m.Person).WithMany(p => p.Memberships).HasForeignKey(p => p.PersonNumber);
HasRequired(m => m.Account).WithMany().HasForeignKey(a => a.AccountNumber);

//In Persons Configuration Class
ToTable("person");
HasKey(p => p.Id);
HasMany(p => p.Memberships).WithOptional(m => m.Person).HasForeignKey(p => p.PersonNumber);

An account can not exist without members ...

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM