首页 > 解决方案 > 如何映射 Nullable(或任何其他可为空的自定义结构)在 Entity Framework Core 5/6 中?

问题描述

采用以下 Entity Framework Core 实体类:

public interface IEntity
{
    public Ulid Id { get; set; }
}

public class User : IEntity
{
    [Key]
    public Ulid Id { get; set; }
    public string Email { get; set; } = default!;
    public string FirstName { get; set; } = default!;
    public string LastName { get; set; } = default!;
    public Ulid? CompanyId { get; set; }

    // Navigation properties
    public Company? Company { get; set; } = default!;
}

请注意,主键是不可为空的 Ulid,它是在此第 3 方库中定义的结构,允许在数据库之外生成可排序的唯一标识符。

根据此处的库说明,我将 Ulid 映射到bytea实体框架中的 PostgreSQL 列,DbContext如下所示:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    var bytesConverter = new UlidToBytesConverter();

    foreach (var entityType in modelBuilder.Model.GetEntityTypes())
    {
        // Don't use database-generated values for primary keys
        if (typeof(IEntity).IsAssignableFrom(entityType.ClrType))
        {
            modelBuilder.Entity(entityType.ClrType)
                .Property<Ulid>(nameof(IEntity.Id)).ValueGeneratedNever();
        }

        // Convert Ulids to bytea when persisting
        foreach (var property in entityType.GetProperties())
        {
            if (property.ClrType == typeof(Ulid) || property.ClrType == typeof(Ulid?))
            {
                property.SetValueConverter(bytesConverter);
            }
        }
    }
}

public class UlidToBytesConverter : ValueConverter<Ulid, byte[]>
{
    private static readonly ConverterMappingHints DefaultHints = new ConverterMappingHints(size: 16);

    public UlidToBytesConverter(ConverterMappingHints? mappingHints = null)
        : base(
                convertToProviderExpression: x => x.ToByteArray(),
                convertFromProviderExpression: x => new Ulid(x),
                mappingHints: DefaultHints.With(mappingHints))
    {
    }
}

此映射适用于不可为空的 Ulid,但User.CompanyId无法映射该属性,因为它可以为空(这反映了 aUser可选属于 a的事实Company)。具体来说,我收到以下错误:

System.InvalidOperationException: The property 'User.CompanyId' could not be mapped because it is of type 'Nullable<Ulid>', which is not a supported primitive type or a valid entity type. Either explicitly map this property, or ignore it using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelValidator.ValidatePropertyMapping(IModel model, IDiagnosticsLogger`1 logger)
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelValidator.Validate(IModel model, IDiagnosticsLogger`1 logger)
...

是否可以在 EF Core 5/6 中映射自定义可为空的结构类型,如果可以,如何映射?我花了几个小时搜索实体框架文档、Google 和 Github,但没有成功找到明确的答案。

标签: c#.netentity-frameworkentity-framework-coredbcontext

解决方案


经过大量的进一步实验,我发现我最初问题中的错误消息最终是一个红鲱鱼,并且只需要使用UlidToBytesConverter继承自ValueConverter

问题似乎是由于使用自定义类型作为主键和外键破坏了 EF Core 的基于约定的外键属性映射(例如,自动映射CompanyIdCompany导航属性)。我找不到任何描述此行为的文档。

因此,EF Core 试图创建一个新属性CompanyId1,并且由于某种原因没有应用值转换器。

ForeignKey解决方案是为属性添加属性CompanyId,如下所示:

public class User : IEntity
{
    [Key]
    public Ulid Id { get; set; }
    public string Email { get; set; } = default!;
    public string FirstName { get; set; } = default!;
    public string LastName { get; set; } = default!;
    [ForeignKey(nameof(Company))]
    public Ulid? CompanyId { get; set; }

    // Navigation properties
    public Company? Company { get; set; } = default!;
}

推荐阅读