簡體   English   中英

如何在實體框架中動態生成包含

[英]How to dynamically generate Includes in entity framework

好吧,我不確定之前是否提出這個問題,但我不知道如何搜索它。 那么這不是實體框架指定的問題,但我將舉例說明使用它。

所以在EF中我們需要使用.Include("Related Object")來包含相關數據。 但是,我想要的是編寫一個方法,該方法接受字符串List並返回具有相關對象的實體或實體列表。

在例子中

public List<Entity> GetAll(List<string> includes>)
{
     List<Entity> entites = context.Entites;
     foreach(string s in includes)
     {
          entites.Include(s);
     }
     return entites;
}

顯然上面的例子不起作用,因為我在宣布列表時已經調出了Entites。 但我認為這證明了這一點。

將您的局部變量聲明為DbQuery<Entity> ,重新分配Include調用的結果並在循環后調用ToList

public List<Entity> GetAll(List<string> includes>)
{
     DbQuery<Entity> entites = context.Entites;
     foreach(string s in includes)
     {
          entities = entites.Include(s);
     }
     return entites.ToList();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM