EF Core 8中不可变复杂类型实体的迁移问题
解决EF Core 8不可变复杂类型构造函数绑定错误
错误原因
执行Add-Migration时的报错核心是:EF Core无法将不可变Address复杂类型的构造函数参数与对应属性绑定。EF Core默认要求构造函数参数名称和映射属性名称大小写完全匹配,你的代码中构造函数参数用了小写开头的line1/line2等,而属性是大写开头的Line1/Line2,导致无法匹配关联,进而抛出找不到合适构造函数的错误。
解决方案
方案1:统一构造函数参数与属性名称(推荐)
修改Address类的主构造函数参数名称,使其和对应属性名称完全一致(包括大小写):
[ComplexType] public class Address(string Line1, string? Line2, string City, string Country, string PostCode) { [MaxLength(250)] [Column("Line1")] public string Line1 { get; } = Line1; [MaxLength(250)] [Column("Line2")] public string? Line2 { get; } = Line2; [MaxLength(100)] [Column("City")] public string City { get; } = City; [MaxLength(100)] [Column("Country")] public string Country { get; } = Country; [MaxLength(100)] [Column("PostCode")] public string PostCode { get; } = PostCode; }
方案2:显式配置构造函数绑定
如果不想修改参数名称,可在DbContext的OnModelCreating方法中手动指定构造函数与属性的绑定关系:
protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.ComplexType<Address>() .HasConstructor(address => new Address( address.Line1, address.Line2, address.City, address.Country, address.PostCode)); }
验证
修改后重新执行Add-Migration命令,即可正常生成迁移文件。
内容的提问来源于stack exchange,提问作者mnu-nasir
相关产品推荐
相关产品推荐

