'ONE (Person) to MANY (PersonTypes) in Code first does not create relationship in DB
I have a person object
public Person {
public string FullName { get; set; }
public DateOfBirth DateOfBirth { get; set; }
public ICollection<PersonTypeLookup> PersonTypes {get; set;}
}
I have a set of pre determined PersonTypeLookup types.
public PersonTypeLookup(int id, string code, string displayName )
{
id = id;
this.Code = code;
this.DisplayName = displayName;
}
I want a person to be many different Person Types so how can a ONE (person) have MANY (personTypeLookups) how can this be done,
public void Configure(EntityTypeBuilder<Person> configuration)
{
....
configuration.HasMany(i => i.PersonTypes).WithOne().OnDelete(DeleteBehavior.Cascade);
....
}
Ive tried adding the above to Person config, but when i build my DB using code first there is no link set up between the two tables in the database, I need this info ?
Solution 1:[1]
Can a single person be of multiple types? If not, than this is a one-to-many relationship, but the other way around. If yes, than this is a many-to-many relationship.
One-to-many design:
public class Person {
public int Id { get; set; }
public string FullName { get; set; }
public DateOfBirth DateOfBirth { get; set; }
public int PersonTypeId { get; set; }
public PersonType PersonType { get; set;}
}
public class PersonType {
public int Id { get; set; }
public string Code { get; set; }
public string DisplayName { get; set; }
public virtual ICollection<Person> Persons { get; set; }
}
Many-to-many design:
public class Person {
public int Id { get; set; }
public string FullName { get; set; }
public DateOfBirth DateOfBirth { get; set; }
public virtual ICollection<PersonType> PersonTypes { get; set;}
}
public class PersonType {
public int Id { get; set; }
public string Code { get; set; }
public string DisplayName { get; set; }
public virtual ICollection<Person> Persons { get; set; }
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Oliver |
