Vreau să-semințe de date cu EfCore meu Deținute de Entități care pot fi nullable
Entități:
public class RootEntity
{
protected RootEntity() { }
public Guid Id { get; set; }
public OwnedEntityLevel1? OwnedEntityLevel1 { get; set; } // can be nullable
}
public class OwnedEntityLevel1
{
public Guid Id { get; set; }
}
Modelul de configurare pentru DbContext:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<RootEntity>(b =>
{
b.OwnsOne(x => x.OwnedEntityLevel1, ob =>
{
ob.HasData(RootEntity.All.Select(x => new
{ x.OwnedEntityLevel1?.Id, RootEntityId = x.Id }));
});
b.HasData(RootEntity.All.Select(x => new { x.Id }));
});
}
Atunci când încerc să-mi creez migrației cu:
dotnet ef migrations add Initial --context NullableObjectDbContext -o Migrations/NullableObject
primesc eroarea:
Sămânța entitate tip de entitate 'OwnedEntityLevel1' nu poate fi adăugat pentru că nicio valoare nu a fost furnizat pentru proprietatea necesare "Id".
Mesajul în schimb este corectă. Dar eu nu inteleg daca ai putea semințe poate fi nul obiecte cu .HasData
într-un fel?
Datele sunt încercarea de a semințelor:
public static RootEntity PredefinedEntity11 { get; } =
new(
Guid.Parse("96e1d442-bdd0-4c6f-9d01-624b27abbac3"),
new OwnedEntityLevel1
{
Id = Guid.Parse("8f8eea73-0b43-412a-b0aa-a9338db6e067")
}
);
public static RootEntity PredefinedEntity12 { get; } =
new(
Guid.Parse("aae51dac-016e-472e-ad51-2f09f8cb9fbb"),
null! // When i add this the migration fails with The seed entity for entity type 'OwnedEntityLevel1' cannot be added because no value was provided for the required property 'Id'
);
public static IReadOnlyList<RootEntity> All { get; } =
new List<RootEntity>(new[] { PredefinedEntity11, PredefinedEntity12 }).AsReadOnly();
Am meu program normal de curgere pot adăuga null obiecte fără nici o problemă:
var ctx = new NullableObjectDbContext();
var rootEntity = new RootEntity(Guid.NewGuid(), null);
ctx.Add(rootEntity);
ctx.SaveChanges();
Am creat un minim reproductibile exemplu aici: https://github.com/enterprisebug/EfCoreHasDataNestedOwnedTypes/tree/main/EfCoreHasDataNestedOwnedTypes/NullableObject
null
valori este super simplă soluție. M-am gândit niciodată la asta! Apreciem dvs. de intrare!