从DbContext动态调用表名

时间:2017-07-07 01:36:06

标签: c# asp.net-mvc entity-framework dbcontext

我知道我可以从这样的特定表中获取记录列表:

var artists = db.Artists.ToList();

但是,我正在尝试为我的许多对象类创建验证工厂,我想发送一个包含表名的字符串(带有命名空间),然后调用该表。

我试过这个:Dynamic table name in linq

我的DbContext中有以下内容:

    public DbSet Set(string name)
    {
        // you may need to fill in the namespace of your context
        return base.Set(Type.GetType(name));
    }

然后我有了这个(.Where没有工作):

using (var db = new ApplicationDBContext())
{
    // Since your DbSet isn't generic, you can can't use this:
    // db.Set("Namespace.EntityName").AsQueryable().Where(a=> a.HasSomeValue...
    // Your queries should also be string based.
    // Use the System.Linq.Dynamic nuget package/namespace
    var results = db.Set("x.Models.Music.Artist")
      .AsQueryable()
      .Where("Name != null") //Just an example
      ;

    //Do something to validate
}

我得到'IQueryable' does not contain a definition for 'Where' and no extension method 'Where' accepting a first argument of type 'IQueryable' could be found (are you missing a using directive or an assembly reference?)

我确定这是一个简单的解决方法,但目前还不确定如何解决。

0 个答案:

没有答案