如何在Entity Framework中将多个实体合并为一个并映射到单表
实现方案
你要的这个效果是Entity Framework(EF Core)里**值对象/所属实体(Owned Entity)**的典型使用场景,有两种常用实现方式:
方案1:用数据注解快速实现
- 直接给
Birth类添加[Owned]标记即可,需要先引用命名空间Microsoft.EntityFrameworkCore
using Microsoft.EntityFrameworkCore; // 标记为所属实体 [Owned] public class Birth { public int Year { get; set; } public int Month { get; set; } public int Day { get; set; } } public class Person { // 注意你原代码里set后的冒号是笔误,这里修正为分号 public int Id { get; set; } public string Name { get; set; } public Birth Date { get; set; } }
- 这个方案默认生成的表列名会带
Date_前缀,也就是Date_Year、Date_Month、Date_Day,如果要完全符合你要的无前缀列名,用下面的Fluent API方案更灵活。
方案2:用Fluent API配置(更推荐,可控性更高)
不需要给实体类加任何特性,直接在你的自定义DbContext的OnModelCreating方法里添加如下配置即可:
protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Person>(person => { person.OwnsOne(p => p.Date, birth => { // 自定义映射的列名,完全匹配你要求的结构 birth.Property(b => b.Year).HasColumnName("Year"); birth.Property(b => b.Month).HasColumnName("Month"); birth.Property(b => b.Day).HasColumnName("Day"); }); }); }
配置完成后,EF会自动把Birth类的三个属性平铺映射到Person对应的数据表中,你代码里可以继续保留Birth的层级结构,不需要手动把属性复制到Person类里,读写数据时直接用person.Date.Year这种写法即可,EF会自动处理和表字段的映射。
内容的提问来源于stack exchange,提问作者Whishare
相关产品推荐
相关产品推荐

