고 싶은 씨앗으로 데이터 EfCore 내 소유의 엔티티가 될 수 있는 사람 nullable
체:
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; }
}
모델 구성 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 }));
});
}
을 만들려고 할 때에 내 마이그레이션:
dotnet ef migrations add Initial --context NullableObjectDbContext -o Migrations/NullableObject
내가 오류가 나타납:
씨앗은 엔터티를 위한 엔터티를 형'OwnedEntityLevel1'에 추가할 수 없기 때문에 값이 없는 제공에 대한 필요성'Id'.
메시지 oviously 올바른 것입니다. 그러나 내가 이해하지 못하는 경우를 수 있는 씨앗 널체 .HasData
어떻게 든?
데이터하려 하는데 씨앗:
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();
내 프로그램으로 정상적인 흐름을 추가할 수 있습니다 널 개체없이 문제가:
var ctx = new NullableObjectDbContext();
var rootEntity = new RootEntity(Guid.NewGuid(), null);
ctx.Add(rootEntity);
ctx.SaveChanges();
들을 재현 가능한 최소한의 예에 여기: https://github.com/enterprisebug/EfCoreHasDataNestedOwnedTypes/tree/main/EfCoreHasDataNestedOwnedTypes/NullableObject
null
값은 간단한 솔루션을 제공합니다. 나는 그것에 대해 생각하지 않았다! 정말로 감사합니다.