[英]Entity Framework returning null children, underlying SQL is fine
我目前正在使用連接到Pervasive數據庫的Entity Framework遇到空子值的奇怪問題。 我是新手,所以我的術語可能是錯誤的。
我有兩個班,我們將其稱為“父母和孩子”。 這是它們的設置方式:
public class Parent
{
public int ParentUK { get; set; }
public int ParentName { get; set; }
public int Status { get; set; }
public virtual IList<Child> Children { get; set; }
}
帶有映射文件
public class Parent_Map : SchemaNameEntityTypeConfiguration<Parent>
{
public Parent_Map(string schemaName)
: base(schemaName)
{
ToTable("Parent");
HasKey(p => p.ParentUK);
Property(p => p.ParentUK)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(p => p.ParentName)
.IsRequired();
Property(p => p.Status)
.IsRequired();
HasMany(p => p.Children)
.WithRequired()
.HasForeignKey(c => c.ParentUK);
}
}
和兒童班
public class Child
{
public int ParentUK { get; set; }
public int Sequence { get; set; }
public int ChildName { get; set; }
}
對應:
public class Child_Map : SchemaNameEntityTypeConfiguration<Child>
{
public Child_Map(string schemaName)
: base(schemaName)
{
ToTable("Child");
HasKey(t => t.ParentUK);
HasKey(t => t.Sequence);
Property(t => t.ParentUK)
.IsRequired();
Property(t => t.Sequence)
.IsRequired();
Property(t => t.ChildName)
.IsRequired();
}
}
當我運行以下查詢時,我希望得到一個包含2個父母(每個孩子3個孩子)的列表。
var result = context.Parents
.Include(p => p.Children)
.Where(p => p.ParentUK < 3);
foreach (var thing in result)
{
if (thing.Children != null)
{
Console.WriteLine(thing.ParentName+ " has some children " + thing.Children.Count);
}
else
{
Console.WriteLine(thing.ParentName+ " has NO children ");
}
}
我已驗證基礎SQL包括兩個表之間的聯接並返回6行。
我正在努力解決的問題是,第一個結果確實包含一個子列表,但是第二個結果的列表為null。 如果我在查詢單個ID之后運行查詢,則一切正常,因此我不知道映射是否有問題。
如果我以更多結果運行查詢,它將類似於
P1 has some children 3
P2 has NO children
P3 has NO children
P4 has NO children
P5 has some children 3
P6 has NO children
P7 has NO children
P8 has NO children
如果我以延遲加載的方式運行查詢,則會得到類似的結果,但P7將具有子項,而P5將不會。
這是一個通用示例,但應該可以說明我的問題。 我真的不確定EF為什么要努力填充列表。 它不會引發任何異常,但是我不確定它是否靜默地記錄在某處。
嘗試更換...
HasKey(t => t.ParentUK);
HasKey(t => t.Sequence);
...通過...
HasKey(t => new { t.ParentUK, t.Sequence });
...這是定義組合鍵的正確方法。 在原始映射中, HasKey(t => t.Sequence)
覆蓋HasKey(t => t.ParentUK)
因此EF僅將Sequence
視為鍵。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.