Zej*_*jji 5 .net c# entity-framework dbcontext entity-framework-core
采用以下 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!;
}
Run Code Online (Sandbox Code Playgroud)
请注意,主键是一个不可为 null 的 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))
{
}
}
Run Code Online (Sandbox Code Playgroud)
此映射适用于不可为空的 Ulids,但无法映射该属性,因为它可以为空(这反映了 a可选属于 a 的User.CompanyId事实)。具体来说,我收到以下错误:UserCompany
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)
...
Run Code Online (Sandbox Code Playgroud)
是否可以在 EF Core 5/6 中映射自定义可为 null 的结构类型,如果可以,如何映射?我花了几个小时搜索实体框架文档、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!;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1477 次 |
| 最近记录: |