【问题标题】:Generic method to get a list for each Entity Framework class获取每个实体框架类的列表的通用方法
【发布时间】:2018-06-06 14:57:34
【问题描述】:

我的实体框架类 (v6) 有这个方法可以从我的数据库中获取此表中的所有元素:

List<FooClass> GetAll_FooClass()
{
    return dbContext.FooClass.ToList();
}

所以我想要的是一种方法,它可以做同样的事情,但可以在我拥有的每个实体类上使用(我的意思是单独的)。

有可能吗?如果可以,我该如何实施?

编辑:我似乎把 FooClass 误认为是一个类,而它是 dbContext 对象的一个​​属性。

public class MyDbContext : DbContext
{
    public MyDbContext()
    { }

    public virtual DbSet<FooClass> FooClass { get; set; }
}

所以我现在正在尝试使用 System.TypePropertyInfoMethodInfo)。

【问题讨论】:

  • dbContext.Set&lt;TypeOfEntity&gt;().ToList()?
  • 使用@DavidG 的答案并使您当前的方法通用
  • 旁注 => 我想您可能会看一些编码约定,因为像 GetAll_myEntityClass 这样的命名是如此...
  • 我尝试了@DavidG 的建议并从 Visual Studio 收到了此通知:'DbContext.Set' 是一种方法,在给定的上下文中无效。所以我混淆了当前的 FooClass 这是一个属性whithin MyDbContext 类与它命名的实体类:public class MyDbContext : DbContext { public virtual DbSet&lt;FooClass&gt; FooClass { get; set; } }

标签: c# entity-framework generics reflection


【解决方案1】:

您可以使用获取实体类型的通用方法。例如:

public List<TEntity> GetAll<TEntity>() 
    where TEntity : class //This is important as the Set method requires it
{
    //Obviously don't do this, but for completeness:
    var dbContext = new MyContext();

    //And here is the real 'magic':
    return dbContext.Set<TEntity>().ToList();
}

要使用它,假设您的上下文如下所示:

public class MyContext : DbContext
{
    public DbSet<Zombie> Zombies { get; set; }
    public DbSet<Human> Humans { get; set; }
}

你可以这样称呼它:

var allOfTheZombies = GetAll<Zombie>();

【讨论】:

  • 好吧,现在它开始工作了。我不知道有什么不同(也许我忘了使用“where T : class”)。谢谢!
  • 我只需要看看如何让它在我的单元测试中使用模拟 (Moq) 上下文。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-26
  • 1970-01-01
  • 2013-08-05
  • 2011-08-03
相关资源
最近更新 更多