ฉันต้องการเพื่อเมล็ดพันธ์ข้อมูลกับ EfCore ต้องของฉันเป็นเจ้าของ Entities ใครจะเป็น nullable
Entities:
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 }));
});
}
ตอนที่ฉันพยายามจะสร้างของฉัน migration กับ:
dotnet ef migrations add Initial --context NullableObjectDbContext -o Migrations/NullableObject
ฉันได้รับข้อผิดพลาด:
อร์ดของดินแดนเวลทั้งรายการสำหรับรายการชนิด'OwnedEntityLevel1'ไม่สามารถเพิ่มเพราะว่าไม่มีค่าเป็นเตรียมไว้ให้สำหรับการทรัพย์สิน'หมายเลข'.
ข้อความ oviously นถูกต้อง แต่ฉันไม่เข้าใจถ้าคุณสามารถเมล็ดพันธ์ nullable กับวัตถุ .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();
ฉันของฉันปกติโครงการไหลเวียนฉันสามารถเพิ่ม nullable วัตถุไม่มีปัญหา:
var ctx = new NullableObjectDbContext();
var rootEntity = new RootEntity(Guid.NewGuid(), null);
ctx.Add(rootEntity);
ctx.SaveChanges();
ฉันต้องสร้างมีขนาดเล็กที่สุด reproducible ตัวอย่างที่นี่: https://github.com/enterprisebug/EfCoreHasDataNestedOwnedTypes/tree/main/EfCoreHasDataNestedOwnedTypes/NullableObject
null
ค่าเป็นสุดยอดวิธีแก้ปัญหาได้ง่าย ฉันไม่เคยคิดเลยว่าเรื่องมัน! ขอบข้อมูลของคุณ!