Eu quero semente de dados com EfCore a minha Propriedade de Entidades que podem 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; }
}
Modelo de configuração para o 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 }));
});
}
Quando tento criar a minha migração com:
dotnet ef migrations add Initial --context NullableObjectDbContext -o Migrations/NullableObject
recebo a mensagem de erro:
A semente de entidade para entidade tipo 'OwnedEntityLevel1' não pode ser adicionado porque nenhum valor foi fornecido para a propriedade "Id".
A mensagem oviously está correto. Mas eu não entendo, se você poderia semente anulável objetos com .HasData
de alguma forma?
Os dados que eu estou tentando semente:
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();
Eu meu fluxo normal do programa que eu possa adicionar anulável objetos sem um problema:
var ctx = new NullableObjectDbContext();
var rootEntity = new RootEntity(Guid.NewGuid(), null);
ctx.Add(rootEntity);
ctx.SaveChanges();
Eu criei um mínimo de exemplo pode ser reproduzido aqui: https://github.com/enterprisebug/EfCoreHasDataNestedOwnedTypes/tree/main/EfCoreHasDataNestedOwnedTypes/NullableObject
null
valores é super simples solução. Eu nunca pensei sobre isso! Realmente apreciamos sua participação!