Entity Framework Core 8 的不可变复杂类型实体的迁移问题

问题描述 投票:0回答:1

我在我的项目中使用 EF Core 8。我正在尝试使用不可变的复杂类型实体。

这是我的代码:

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

这是我的主要实体:

public class Customer
{
    public required Guid Id { get; set; }
    public required string Title { get; set; }
    public string? FirstName { get; set; }
    public string? LastName { get; set; }    
    public Address? Address { get; set; }        
}

现在,当我运行命令

Add-Migration
时,我收到以下错误:

无法创建类型为“”的“DbContext”。异常“没有找到适合实体类型“Account”的构造函数。地址#地址'。以下构造函数的参数无法绑定到实体类型的属性:
无法在 'Account.Address#Address(string line1, string line2, string city, string Country, string postCode)' 中绑定 'line1'、'line2'、'city'、'country' 或 'postCode' 请注意,仅映射属性可以绑定到构造函数参数。无法绑定对相关实体的导航,包括对拥有类型的引用。尝试创建实例时抛出。有关设计时支持的不同模式,请参阅 https://go.microsoft.com/fwlink/?linkid=851728

entity-framework-core .net-8.0
1个回答
0
投票

这就是问题吗,“请注意,只有映射的属性才能绑定到构造函数参数”

来自 .. 的文档带有构造函数的实体类型

只读属性

一旦通过构造函数设置属性,将其中一些设置为只读就有意义了。 EF Core 支持这一点,但有一些事情需要注意:

没有 setter 的属性不会按照约定进行映射。 (这样做往往会映射不应映射的属性,例如计算属性。) 使用自动生成的键值需要一个可读写的键属性,因为插入新实体时需要由键生成器设置键值。

避免这些事情的一个简单方法是使用私有设置器

EF Core 将具有私有 setter 的属性视为可读写,这意味着所有属性都像以前一样映射,并且密钥仍然可以存储生成。

© www.soinside.com 2019 - 2024. All rights reserved.