【问题标题】:How to combine several entities into one in entity framework (map complex entity into single table)如何在实体框架中将多个实体合二为一(将复杂实体映射到单个表中)
【发布时间】:2021-10-21 11:45:19
【问题描述】:

例如。我有两个模型

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; }
}

如何让实体框架看到这样的“Person”实体:

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; }
}

即EF 应该将其映射到单个表中。

【问题讨论】:

  • 你能再解释一下吗。 “看到”是指 EF 应该将其映射到单个表或其他东西吗?
  • 您可以在模型文件夹中创建一个自定义类,其名称为“CombinedPersonBirth”,然后在该类中创建一个 Person 类型的属性和数据类型 Birth 的第二个属性。然后在你的视图和控制器中使用这个类。
  • @GuruStron 是的,我是认真的。

标签: c# .net entity-framework entity-framework-core


【解决方案1】:

如果您使用的是 EF Core,这可以通过所谓的"Owned Entities" 来实现。使用属性:

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; }
}

或显式配置:

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

请注意,Birth 字段将带有前缀。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-17
  • 1970-01-01
  • 2013-02-18
  • 2014-08-21
  • 1970-01-01
  • 2011-01-04
  • 1970-01-01
相关资源
最近更新 更多