【问题标题】:ASP.NET Core 2.0 Get a List of Models and then get the Model Columns - options for thisASP.NET Core 2.0 获取模型列表,然后获取模型列 - 此选项
【发布时间】:2017-12-04 16:15:08
【问题描述】:

ASP.NET Core 2.0 获取模型列表,然后获取模型列 - 我有哪些选择?我正在努力完成两个关键项目。 1. 使用 GetModels() 从 ApplicationDBContext 中获取模型列表。这部分工作正常,我得到一个模型列表。 2. 使用 GetModelColumns 从模型中获取列列表,并将模型名称作为字符串传递。如何获得 PropertyInfo 的结果?

由于我无法实例化新的 PropertyInfo(),我应该使用 typeof 吗?

使用 System.Reflection;

    public static List<PropertyInfo> GetModels()
    {
        //Get the list of Models in ApplicationDbContext
        var propertyInfoList = typeof(ApplicationDbContext).GetProperties().ToList();
        return propertyInfoList;
    }

    public static PropertyInfo GetModelColumns(string modelName)
    {
        //return the Columns associated with the Model
    //How should this be done?
        //Cannot instatiate a new PropertyInfo()
        //Use typeof?           
        var propertyInfo = new PropertyInfo();
        var propertyInfoList = GetModels();
        propertyInfo = propertyInfoList.Single(s => s.Name == modelName);
        return propertyInfo;
    }

    public async Task<IActionResult> DetailsAsync(string? modelName)
    {
    string strColumnName="";
    var myModel = GetModelColumns(modelName));
    foreach(var item in myModel)
        {
           strColumnName=item.Name; 
        }
}

【问题讨论】:

  • 究竟是什么不在这里工作?你不能说它“不工作”,然后指望我们猜出我害怕的问题。
  • 我正在寻找 GetModels() 的编码选项。这里的代码不起作用。这只是我认为它应该如何工作的一个示例

标签: c# asp.net-core-2.0


【解决方案1】:

我会稍有不同。当您只需要一个模型时,获取上下文的所有属性是没有意义的。其次,属性类型将是DbSet&lt;T&gt;,因此您需要获取泛型类型。所以你可以这样做:

public static IEnumerable<string> GetColumns<TEntity>(string modelName)
{
    var property = typeof(TEntity)
        .GetProperties()
        .Single(s => s.Name == modelName);

    return property.PropertyType
        .GetGenericArguments() //Get the generic type of the DbSet
        .SelectMany(t => t.GetProperties()
            .Select(pi => pi.Name));
}

您可能应该对此进行一些类型检查和验证,但这可以这样调用:

var columns = GetColumns<ApplicationDbContext>("SomeProperty");

【讨论】:

    猜你喜欢
    • 2018-09-02
    • 1970-01-01
    • 2014-04-03
    • 1970-01-01
    • 1970-01-01
    • 2014-05-09
    • 2014-05-10
    • 2011-03-07
    • 2017-11-15
    相关资源
    最近更新 更多