Reputation: 1735
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?
Upvotes: 0
Views: 169
Reputation: 1735
I ended up changing the model class to
Upvotes: 0
Reputation: 15772
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();
}
}
Upvotes: 1