【问题标题】:How do I programmatically query a DbSet in a DbContext?如何以编程方式查询 DbContext 中的 DbSet?
【发布时间】:2012-03-21 12:22:07
【问题描述】:

我正在尝试构建一个控制器,为我的所有查找表的编辑请求提供服务。我的 DbContext 上有几个从 IdNamePairBase 派生的 DbSet 变量,例如:

public DbSet<Country> Countries { get; set; } // Country derives from IdNamePairBase

如何将其中一个的名称传递给查询,以获取该列表中的所有项目?例如

var list = db.GetNamedDbSet("Countries");

然后,我需要从list 获得IEnumerable&lt;IdNamePairBase&gt; 以获得奖励积分。

【问题讨论】:

    标签: c# .net entity-framework ef-code-first


    【解决方案1】:

    如果表的名称与类型相对应,您可以在 DbContext 上使用 Set(Type type)

     public IEnumerable<IdNamePairBase> GetNamedDbSet(string dbSetName)
     {
          var property = Type.GetType(dbSetName);
          if (property == null || !property.CanRead)
          {
             throw new ArgumentException("DbSet named " + dbSetName + " does not exist." );
          }
    
          // at this point you might want to check that the property is an enumerable type
          // and that the generic definition is convertible to IdNamePairBase by
          // inspecting the property type.  If you're sure that these hold, you could
          // omit the check.
    
          return Set(type).Cast<IdNamePairBase>();
     }
    

    原答案

    如果集合的名称与属性名称匹配,则可以使用反射。

     public IEnumerable<IdNamePairBase> GetNamedDbSet( string dbSetName )
     {
          var property = this.GetType().GetProperty( dbSetName );
          if (property == null || !property.CanRead)
          {
             throw new ArgumentException("DbSet named " + dbSetName + " does not exist." );
          }
    
          // at this point you might want to check that the property is an enumerable type
          // and that the generic definition is convertible to IdNamePairBase by
          // inspecting the property type.  If you're sure that these hold, you could
          // omit the check.
    
          var result = new List<IdNamePairBase>();
          foreach (var item in (IEnumerable)property.GetValue( this, null))
          {
              result.Add( (IdNamePairBase)item );
          }
          return result;
     }
    

    【讨论】:

    • 我从反射中得到了属性值,谢谢,但我希望首先将动态类型转换为正确的 DbSet 类型。我会尽快更新问题。
    • @ProfK - 这比我想象的要棘手,因为要获得正确 DbSet 的强类型(通用)方法,您必须知道类型。如果您知道类型,那么您应该能够简单地使用适当的属性。我怀疑一个可以轻松完成的非泛型 DbSet 是否可行。
    • GetNamedDbSet 正是我需要的,但 Visual Studio 找不到 IdNamePairBase 定义。我正在尝试为它制作 DbContext 扩展类!该怎么办 ?帮助。
    • @Add080bbA 使用你自己的类名。此答案中的一个是针对该问题的。
    • 如果没有确定怎么办!假设我想要一个名为 "employees" 或 "firms" 的数据库集的关键属性集合。我想我不明白解决方案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多