Quiero semilla de datos con EfCore a mi Entidades de Propiedad que puede ser nullable
Entidades:
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; }
}
La configuración del modelo de 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 }));
});
}
Cuando trato de crear mis migración con:
dotnet ef migrations add Initial --context NullableObjectDbContext -o Migrations/NullableObject
recibo el error:
La semilla de la entidad por tipo de entidad 'OwnedEntityLevel1' no se puede agregar porque no hay ningún valor fue proporcionada por la propiedad required 'Id'.
El mensaje oviously es correcta. Pero no entiendo si pudiera semilla de los objetos con los que aceptan valores null .HasData
de alguna manera?
Los datos que yo estoy tratando de semilla:
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();
Yo mi programa normal de flujo que puedo añadir que aceptan valores null objetos sin problemas:
var ctx = new NullableObjectDbContext();
var rootEntity = new RootEntity(Guid.NewGuid(), null);
ctx.Add(rootEntity);
ctx.SaveChanges();
He creado una mínima reproducible ejemplo aquí: https://github.com/enterprisebug/EfCoreHasDataNestedOwnedTypes/tree/main/EfCoreHasDataNestedOwnedTypes/NullableObject
null
los valores de la super simple solución. Yo nunca pensé en ello! Realmente apreciamos su opinión!