如何以编程方式查询DbContext中的DbSet?

时间:2012-03-21 12:22:07

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

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

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

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

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

然后,对于奖励积分,我需要从IEnumerable<IdNamePairBase>获得list

1 个答案:

答案 0 :(得分:0)

如果表的名称对应于类型,则可以在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;
 }