0

I'm trying to create these three models in EF 4.3:

 - Family
  - Guid FamilyId
  - ICollection< Person> Members
 - Company
  - Guid CompanyId
  - ICollection< Person> Employees
 - Person
  - Guid PersonId
  - String Name

A person can belong to multiple families and multiple companies, as well as doesn't belong to any.

After running the code, the mapping in the database seems a bit strange. Family-Members and Company-Employees were not mapped. Also, there are four columns in the Persons table: PersonId, Name, Family_FamilyId and Company_CompanyId.

I think my code is meant to be that a Person will always belong to 1 Family and 1 Company. How should I change the code?

2 Answers 2

1

You can't express all of this information in your classes as you figured out. To add extra information you have a few options.

You can add this to your EF context class

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{ 
    //All people must belong to a family.
    modelBuilder.Entity<Family>().HasMany(x => x.Members)
           .WithRequired();

    //Each person may belong to ZERO-Many companies.
    modelBuilder.Entity<Company>().HasMany(x => x.Employees)
           .WithMany();        
}

Or this to your EF context class

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{ 
    modelBuilder.Configurations.Add(new ComapnyMapper());
    modelBuilder.Configurations.Add(new FamilyMapper());

}

public class FamilyMapper : EntityTypeConfiguration<Family>
{
     public FamilyMapper()
     {
          HasMany(x => x.Members)
           .WithRequired();        
     }
}
public class CompanyMapper : EntityTypeConfiguration<Company>
{
     public CompanyMapper()
     {
          HasMany(x => x.Employees)
           .WithMany();        
     }
}
Sign up to request clarification or add additional context in comments.

Comments

0

I ended up changing the model class to

  • Family
    • Guid FamilyId
    • ICollection< Person> Members
  • Company
    • Guid CompanyId
    • ICollection< Person> Employees
  • Person
    • Guid PersonId
    • String Name
    • ICollection< Family> Families
    • ICollection< Company> Companies

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.