Entity Framework Core值对象内嵌实体外键列名自定义方法问询
EF Core值对象内嵌实体自定义外键列名解决方案
你之前的配置未生效的核心原因是:HasForeignKey方法传入的参数是外键属性(包含影子属性)的名称,而非数据库实际生成的列名,EF Core对Owned类型的所有属性默认会拼接所属导航属性名作为列名前缀,因此需要单独为外键属性指定映射的数据库列名。
解决方案1:显式声明外键属性(推荐)
首先在值对象Measurement中显式定义外键属性,再直接配置该属性的列名:
public class Measurement { public double Value { get; set; } // 新增显式外键属性 public int UOMId { get; set; } public UnitOfMeasure UOM { get; set; } }
对应的Fluent API配置:
var withEntity = modelBuilder.Entity<EntityA>().OwnsOne(t => t.VO); withEntity.Property(e => e.Value).HasColumnName("WithEntityValue"); // 直接配置外键属性对应的列名 withEntity.Property(e => e.UOMId).HasColumnName("WithEntityValueUOMId"); withEntity.HasOne(e => e.UOM).WithMany().HasForeignKey(e => e.UOMId);
解决方案2:使用影子属性配置(无需修改值对象代码)
如果不想改动现有值对象的定义,可以通过配置影子外键属性实现自定义列名:
var withEntity = modelBuilder.Entity<EntityA>().OwnsOne(t => t.VO); withEntity.Property(e => e.Value).HasColumnName("WithEntityValue"); // 先定义影子外键属性,并指定映射的数据库列名 withEntity.Property<int>("UOMId").HasColumnName("WithEntityValueUOMId"); // 关联时使用定义好的影子外键属性 withEntity.HasOne(e => e.UOM).WithMany().HasForeignKey("UOMId");
两种方案都可以生成符合预期的列名WithEntityValueUOMId,不会额外拼接VO_前缀。
内容的提问来源于stack exchange,提问作者user122019
相关产品推荐
相关产品推荐

