c# - EF 6 : mapping complex type collection?

标签 c# entity-framework domain-driven-design complextype value-objects

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

复杂类型只是在您需要的任何地方声明相同成员的简写。您可以在一堆需要联系人数据的其他实体中使用相同的联系人类型,而无需显式定义 AddressPhoneNumberEmail 属性对于每个实体。所以你不能真正在集合中使用它们,因为每次你想向它添加或删除项目时,你都必须从表本身添加或删除列。

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/

相关文章:

sql - 将 BIT 发送到 Entity Framework,但 EF 看到 INT

c# - 如何在 ASP MVC 和 Entity Framework 中访问另一个 Controller 的 View

c# - 生成高斯范围内的随机数?

Visual Studio 中的 C# : How to display a list in a DataGridView? 得到奇怪的东西

c# - LINQ 分组依据然后显示 (dd mmm) 的日期时间

java - 为什么事件源模式中使用事件流?

c# - 领域驱动设计: Using the Domain in the Blazor UI

c# - 在领域驱动设计中,将对其他对象的存储库的调用放在领域对象中会违反 DDD 吗?

c# - 如何使用 c# 将缺少分隔符的字符串解析为 DateTime?

c# - 实体数据网格: best way to add computed values?