EF 6(代码优先)是否支持复杂类型集合(值对象集合)映射?我知道它支持复杂类型,但还没有找到我们拥有复杂类型集合的示例。
例如,假设您有一个名为 Student 的实体,其中包含一组联系人。对于 NH,我可以简单地说 Student 有一个联系人集合,并且该联系人是一个组件(相当于 ef 中的复杂类型)。这可以在不更改与实体的联系的情况下使用 EF 完成吗?
最佳答案
只需为复杂类型中的每个属性添加一列,即可将复杂类型映射到实体表。因此,将联系人作为一个单独的实体:
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;}
}
将生成包含列的 Student 表的映射:
ID
PrimaryContact_Address
PrimaryContact_PhoneNumber
PrimaryContact_Email
SecondaryContact_Address
SecondaryContact_PhoneNumber
SecondaryContact_Email
复杂类型只是在您需要的任何地方声明相同成员的简写。您可以在一堆需要联系人数据的其他实体中使用相同的联系人类型,而无需显式定义 Address
、PhoneNumber
和 Email
属性对于每个实体。所以你不能真正在集合中使用它们,因为每次你想向它添加或删除项目时,你都必须从表本身添加或删除列。
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?
联系人项目实际存储在哪里?你怎么能索引它?如果您尝试这样做,映射器将完全忽略 Contacts 属性。
只需从 Contact 类中删除 ComplexType 即可干净地使用集合。不过,这会在数据库中创建一个表:
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;}
}
关于c# - EF 6 : mapping complex type collection?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29878961/