如何在 Entity Framework Core 5/6 中映射 Nullable<Ulid>(或任何其他可为空的自定义结构)?
How to map Nullable<Ulid> (or any other nullable custom struct) in Entity Framework Core 5/6?
采取以下Entity Framework核心实体class:
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!;
}
请注意,主键是不可为 null 的 Ulid,它是 this 3rd party library 中定义的结构,允许在数据库外部生成可排序的唯一标识符。
我正在将 Ulid 映射到 Entity Framework DbContext
中的 PostgreSQL bytea
列,如下所示,符合库说明 here:
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))
{
}
}
此映射适用于不可为 null 的 Ulids,但 User.CompanyId
属性 无法映射,因为它可以为 null(这反映了 User
可选地属于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 中映射自定义可为 null 的结构类型,如果可以,如何映射?我花了很多时间搜索 Entity Framework 文档、Google 和 Github,但没有成功找到明确的答案。
经过大量的进一步实验,我发现我原来问题中的错误消息最终是一个转移注意力的问题,而使用从 ValueConverter
继承的 UlidToBytesConverter
就是所需要的!
问题似乎是由于使用自定义类型作为主键和外键破坏了 EF Core 的 convention-based mapping 外键属性(例如自动映射 CompanyId
到 Company
导航属性)。我找不到任何描述此行为的文档。
因此,EF Core 正在尝试创建一个新的 属性 CompanyId1
,但由于某些原因未应用值转换器。
解决方案是为 CompanyId
属性 添加 ForeignKey
属性,如下所示:
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!;
}
采取以下Entity Framework核心实体class:
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!;
}
请注意,主键是不可为 null 的 Ulid,它是 this 3rd party library 中定义的结构,允许在数据库外部生成可排序的唯一标识符。
我正在将 Ulid 映射到 Entity Framework DbContext
中的 PostgreSQL bytea
列,如下所示,符合库说明 here:
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))
{
}
}
此映射适用于不可为 null 的 Ulids,但 User.CompanyId
属性 无法映射,因为它可以为 null(这反映了 User
可选地属于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 中映射自定义可为 null 的结构类型,如果可以,如何映射?我花了很多时间搜索 Entity Framework 文档、Google 和 Github,但没有成功找到明确的答案。
经过大量的进一步实验,我发现我原来问题中的错误消息最终是一个转移注意力的问题,而使用从 ValueConverter
继承的 UlidToBytesConverter
就是所需要的!
问题似乎是由于使用自定义类型作为主键和外键破坏了 EF Core 的 convention-based mapping 外键属性(例如自动映射 CompanyId
到 Company
导航属性)。我找不到任何描述此行为的文档。
因此,EF Core 正在尝试创建一个新的 属性 CompanyId1
,但由于某些原因未应用值转换器。
解决方案是为 CompanyId
属性 添加 ForeignKey
属性,如下所示:
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!;
}