【问题标题】:How to dynamically generate Includes in entity framework如何在实体框架中动态生成包含
【发布时间】:2015-07-08 23:55:02
【问题描述】:

嗯,我不确定这个问题之前是否问过,但我不知道如何搜索它。好吧,这不是实体框架指定的问题,但我将举例说明使用它。

所以在 EF 中我们需要使用.Include("Related Object") 来包含相关数据。但是我想要的是编写一个方法,该方法接受一个字符串列表并返回具有相关对象的实体或实体列表。

举例

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

显然上面的例子不起作用,因为我在声明列表时已经调用了实体。但我认为它证明了这一点。

【问题讨论】:

  • 您可以为您的问题使用更好的标题:) 类似How to dynamically generate Includes in entity framework 或类似的东西。您可能希望将entity-framework 标签添加到您的问题中。
  • 嗯,这肯定是一个更好的标题。 :) 但这不是 EF 指定的问题,但您可能是对的。
  • 我接受了你的建议。 :)

标签: c# methods entity-framework-4


【解决方案1】:

将您的局部变量声明为DbQuery&lt;Entity&gt;,将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();
}

【讨论】:

  • 我试试看。
猜你喜欢
  • 1970-01-01
  • 2017-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多