首頁 > 後端開發 > C++ > 如何使用 Include() 在實體框架中包含嵌套屬性?

如何使用 Include() 在實體框架中包含嵌套屬性?

Patricia Arquette
發布: 2025-01-25 06:17:08
原創
274 人瀏覽過

How Can I Include Nested Properties in Entity Framework Using Include()?

Entity Framework中包含巢狀屬性層級

在Entity Framework中使用Include()方法擷取包含相關資料的物件時,一個常見的限制是缺乏對包含多層嵌套屬性的支援。例如,假設您有一個模型,其中ApplicationServers擁有一個ApplicationsWithOverrideGroup集合,而ApplicationsWithOverrideGroup包含Application和CustomVariableGroup屬性。

初始嘗試:

為了包含巢狀屬性,您可以嘗試以下方法:

public IEnumerable<applicationserver> GetAll()
{
    return this.Database.ApplicationServers
        .Include(x => x.ApplicationsWithOverrideGroup)               
        .Include(x => x.ApplicationWithGroupToForceInstallList)
        .Include(x => x.CustomVariableGroups)                
        .ToList();
}
登入後複製

但是,此方法只會填入ApplicationWithOverrideVariableGroup的Enabled屬性,而不會填入Application或CustomVariableGroup屬性。

EF 6的解:

要在EF 6中包含嵌套屬性,請使用接受lambda表達式的Include()的重載:

using System.Data.Entity;

query.Include(x => x.Collection.Select(y => y.Property));
登入後複製

EF Core的解決方案:

在EF Core中,使用ThenInclude方法包含嵌套屬性:

using Microsoft.EntityFrameworkCore;

query.Include(x => x.Collection)
     .ThenInclude(x => x.Property);
登入後複製

透過使用這些方法,您可以急切地載入Entity Framework中的巢狀屬性級別,確保您的物件已完全填入了必要的資料。

以上是如何使用 Include() 在實體框架中包含嵌套屬性?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板