मैं करने के लिए चाहते हैं बीज के साथ डेटा 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 सही है । लेकिन मैं नहीं समझ सकता है अगर आप बीज 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();
मैं एक बनाया है, कम से कम प्रतिलिपि प्रस्तुत करने योग्य उदाहरण यहाँ: https://github.com/enterprisebug/EfCoreHasDataNestedOwnedTypes/tree/main/EfCoreHasDataNestedOwnedTypes/NullableObject
null
मूल्यों है सुपर सरल समाधान है । मैंने कभी नहीं सोचा था इसके बारे में! वास्तव में अपने इनपुट की सराहना!