简体   繁体   English

如何在实体框架中将多个实体合二为一(将复杂实体映射为单表)

[英]How to combine several entities into one in entity framework (map complex entity into single table)

Just for example.举个例子。 I have two models我有两个模型

public class Person {
    public int Id { get; set: }
    public string Name { get; set; }
    public Birth Date { get; set; }
}
public class Birth {
    public int Year { get; set; }
    public int Month { get; set; }
    public int Day { get; set; }
}

How to make the entity framework seeing the 'Person' entity like this:如何让实体框架像这样看到“人”实体:

public class Person {
    public int Id { get; set: }
    public string Name { get; set; }
    public int Year { get; set; }
    public int Month { get; set; }
    public int Day { get; set; }
}

ie EF should map it into single table.即 EF 应将其映射到单个表中。

If you are using EF Core this can be achieved with so called "Owned Entities" .如果您使用的是 EF Core,这可以通过所谓的“拥有的实体”来实现。 Using atrributes:使用属性:

public class Person 
{
    public int Id { get; set: }
    public string Name { get; set; }
    public Birth Date { get; set; }
}

[Owned]
public class Birth 
{
    public int Year { get; set; }
    public int Month { get; set; }
    public int Day { get; set; }
}

Or explicit configuration:或者显式配置:

modelBuilder.Entity<Person>().OwnsOne(p => p.Date);

Note that Birth fields will be prefixed.请注意, Birth字段将带有前缀。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM