Complex types are mapped to the entity's table by just adding a column for each property in the complex type. So, with Contact as a separate entity:
public class Student
{
[Key]
public int ID {get; set;}
public Contact PrimaryContact { get; set; }
public Contact SecondaryContact{ get; set; }
}
[ComplexType]
public class Contact
{
public string Address{get; set;}
public string PhoneNumber{get; set;}
public string Email{get; set;}
}
Will yield a mapping of a Student table that has columns:
ID
PrimaryContact_Address
PrimaryContact_PhoneNumber
PrimaryContact_Email
SecondaryContact_Address
SecondaryContact_PhoneNumber
SecondaryContact_Email
Complex types are just shorthand for declaring the same members wherever you need it. You could use that same Contact type in a bunch of other entities that need contact data without having to explicitly define Address
, PhoneNumber
, and Email
properties for each entity. So you can't really use them in a collection, because every time you wanted to add or remove items to it, you'd have to add or remove columns from the table itself.
public class Student
{
[Key]
public int ID {get; set;}
public ICollection<Contact> Contacts{ get; set; }
}
[ComplexType]
public class Contact
{
public string Address{get; set;}
public string PhoneNumber{get; set;}
public string Email{get; set;}
}
ID
Contacts[x]_Address?
Contacts[x]_PhoneNumber?
Contacts[x]_Email?
Where could Contacts items actually be stored? How could you index it? If you try to do this, the mapper would just ignore the Contacts property altogether.
You can cleanly use collections by just removing the ComplexType from the Contact class. This would create a table in the database, though:
public class Student
{
[Key]
public int ID {get; set;}
public ICollection<Contact> Contacts{ get; set; }
}
public class Contact
{
[Key]
public int ID {get; set;}
public string Address{get; set;}
public string PhoneNumber{get; set;}
public string Email{get; set;}
}