采用以下實(shí)體框架核心實(shí)體類:
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!;
}
注意,主鍵是non-nullableUlid,它是這個(gè)第三方庫(kù)中定義的結(jié)構(gòu),允許在數(shù)據(jù)庫(kù)之外生成可排序的唯一標(biāo)識(shí)符。
我將Ulid映射到實(shí)體框架DbContext
中的PostgreSQLbytea
列,如下所示,按照這里的庫(kù)說(shuō)明:
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))
{
}
}
這個(gè)映射對(duì)于non-nullableulid很好,但是User.CompanyId
屬性不能被映射,因?yàn)樗梢詾閚ull(這反映了User
可以選擇屬于Company
的事實(shí))。具體來(lái)說(shuō),我得到以下錯(cuò)誤:
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)
...
是否可以在efcore5/6中映射自定義的可空結(jié)構(gòu)類型?如果可以,如何映射?我花了幾個(gè)小時(shí)研究實(shí)體框架文檔Google和Github,但沒(méi)有找到一個(gè)明確的答案。
經(jīng)過(guò)大量的進(jìn)一步實(shí)驗(yàn)后,我發(fā)現(xiàn)我原來(lái)問(wèn)題中的錯(cuò)誤信息最終是一條紅鯡魚,使用
UlidToBytesConverter
從ValueConverter
繼承的UlidToBytesConverter
就是所需要的!這個(gè)問(wèn)題似乎是因?yàn)槭褂米远x類型作為主鍵和外鍵會(huì)破壞EF Core的convention-based外鍵屬性映射(例如,自動(dòng)將
CompanyId
映射到Company
導(dǎo)航屬性)。我找不到任何描述這種行為的文件。因此,EF Core試圖創(chuàng)建一個(gè)新屬性
CompanyId1
,但由于某些原因,沒(méi)有應(yīng)用值轉(zhuǎn)換器。解決方案是將
ForeignKey
屬性添加到CompanyId
屬性中,如下所示: