c# - 如何映射 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,但没有成功找到明确的答案。
解决方案
经过大量的进一步实验,我发现我最初问题中的错误消息最终是一个红鲱鱼,并且只需要使用UlidToBytesConverter
继承自ValueConverter
!
问题似乎是由于使用自定义类型作为主键和外键破坏了 EF Core 的基于约定的外键属性映射(例如,自动映射CompanyId
到Company
导航属性)。我找不到任何描述此行为的文档。
因此,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!;
}
推荐阅读
- php - 如何从 laravel 的图像文件夹中删除我的图像?
- c++ - 如何在没有伪影的情况下从“一个”Mipmap 纹理中采样?
- sql - SQL 查询 - 格式化来自同一个表的数据
- android-emulator - 使用“emulator -avd”,如何获得“启动完成”的指示?
- python - 了解sklearn QuantileTransformer
- java - 如何通过 frida js 创建一个 Integer.TYPE(int.class) 数组
- python - RGB通道上的Tensorflow 2D卷积分别?
- python - 我正在尝试从网站上抓取,但它给了我一个错误
- c# - 从存储过程中获取数据到模型 EF6 MVC
- mongodb - 在 MongoDB 中保存喜欢/收藏/评论/关注的最佳方法是什么?