使用Entity Framework在MVC中获取动态表名称

时间:2017-07-28 02:24:46

标签: asp.net-mvc entity-framework linq

我知道这种查询有很多解决方案,但我无法实现其中任何一种。

我正在将表名传递给我的函数,并希望EF获取传递的相应表值的表结果。

所以这是我在Controller中的函数(JsonResult): -

public JsonResult FetchTblData()
{
      string MyTableName= Request.Form["TblName"].ToString();

    using (EBContext db = new EBContext())
    {
        try
        {
            var EduTblList = db.(**MyTableName**).ToList(); // want to implement it here.
        }
        catch (Exception ex)
        {
            string innerMessage = (ex.InnerException != null) ? ex.InnerException.Message : "";
        }

        return new JsonResult { Data = EduTblList, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
    }
}

如果没有太多代码修改和使用EF或LINQ的最简单方法,我怎么能这样做? 请帮助

1 个答案:

答案 0 :(得分:0)

尝试以下代码:

    public JsonResult FetchTblData()
    {
          string MyTableName= Request.Form["TblName"].ToString();

        using (EBContext db = new EBContext())
        {
            try
            {
             Type tableType;
               switch(MyTableName)
                {
                 case "MyTableName":
                    tableType= typeof(TableEntityName);
                   break;
                }
                var dbquery = context.Set(tableType);
                var EduTblList = result.ToList(); // want to implement it here.
            }
            catch (Exception ex)
            {
                string innerMessage = (ex.InnerException != null) ? ex.InnerException.Message : "";
            }

            return new JsonResult { Data = EduTblList, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }
    }