【问题标题】:Determine IQueryable column type based on name根据名称确定 IQueryable 列类型
【发布时间】:2015-05-21 10:53:03
【问题描述】:

我有一个 iQueryable 数据集。

我希望能够根据名称确定数据的类型。

我正在对视图模型进行 linq 查询,我希望从结果查询中按名称获取列的类型

【问题讨论】:

  • 你是指SQL Server类型,还是C#类型?
  • 两者都行,我需要通过名称而不是值来确定列是整数还是字符串。

标签: linq types iqueryable


【解决方案1】:
IQueryable q = ...;
if (q.ElementType.GetProperty("PropertyName").PropertyType == typeof(int))
{
    // PropertyName is an integer property
    . . .
}

【讨论】:

    【解决方案2】:

    不清楚你在问什么...我希望你不想发现 IdIdChildChildIdint 只是因为它们包含单词 @987654325 @...

    为了更理智的“你给我查询和属性的名称,我给你属性的Type”:

    public static class EnumerableEx
    {
        public static Type TypeOf<TSource>(this IQueryable<TSource> source, string propertyName)
        {
            PropertyInfo property = typeof(TSource).GetProperty(propertyName);
    
            return property != null ? property.PropertyType : null;
        }
    
        public static Type TypeOf<TSource, TType>(this IQueryable<TSource> source, Func<TSource, TType> property)
        {
            return typeof(TType);
        }
    }
    

    像这样使用它:

    Type type = query.TypeOf("Id");
    

    或者如果您使用非泛型IQueryable,请使用@shevchenko 的解决方案

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-12
      • 1970-01-01
      • 2013-02-06
      • 1970-01-01
      • 2016-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多