【问题标题】:How to return column names by passing table name using Entity Framework in MVC如何通过在 MVC 中使用实体框架传递表名来返回列名
【发布时间】:2017-06-06 15:25:55
【问题描述】:

到目前为止我尝试过的, 在下面的编码中将“tablename”作为动态字符串传递。

public List GetColumnNames(string tablename)
{
    using (var Context = new MCPEntities())
    {
        var names = typeof(AdministratorInformation).GetProperties().Select(property => property.Name).ToArray();
        return names.ToList();
    }
}

【问题讨论】:

  • 以上代码有什么问题?就像您所做的那样,它可以简单地通过对表类型的反射来实现。仅供参考,您在尝试的方法中不需要上下文或 EF。
  • "string tablename" 是下拉列表选择值(表名),我只想从下拉列表中显示尊重的选择表名的列名。

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


【解决方案1】:

这应该可行。不过我还没有测试过。 创建一个返回特定类型属性列表的方法。如果您使用的是 MVC,那么这可以是一个控制器操作。

public ActionResult ColumnNames(string tableName)
    {
        var columns = Type.GetType("MyNamespace." + tableName).GetProperties().Select(p => p.Name).ToList();
        return Json(columns, JsonRequestBehavior.AllowGet);
    }

将结果绑定到下拉列表。

【讨论】:

  • Getting Null reference exception error here, var columns = Type.GetType(tableName).GetProperties().Select(p => p.Name).ToList();
  • 更新了答案。您需要提供完全限定的路径。
  • “我的命名空间”。是什么意思?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-07
  • 1970-01-01
  • 2011-10-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多