entity framework将列名称提供为字符串变量

我正在寻找获得这样的东西的方法:

string _col1 = "first name"; string _name; var query = from c in ctx.Customers select c; _name = query.FirstOrDefault().[_name]; 

据我所知,我只能获得强类型字段名称,但我想将它们作为字符串变量提供。

我不确定EF是否为您提供了根据属性的字符串名称获取属性值的方法,但您可以使用reflection。

 string name = typeof(Customer) .GetProperty("first name") .GetValue(query.First(), null) as string; 

我猜你正在处理的EF课叫做Customer

你需要使用reflection。 如果您尝试按动态选择的列进行过滤,则可以尝试以下方法:

 string propertyName string keyword ParameterExpression parameter = Expression.Parameter(typeof(YourType), "x"); Expression property = Expression.Property(parameter, propertyName); Expression target = Expression.Constant(keyword); Expression containsMethod = Expression.Call(property, "Contains", null, target); Expression> lambda = Expression.Lambda>(containsMethod, parameter); var companies = repository.AsQueryable().Where(lambda); 

我想要做的是选择一个特定的列,然后你可以使用相同的原理生成lamba表达式并在select中使用它(减去条件)

 var companies = repository.AsQueryable().Where(whatever).Select(lambda); 

出于某种原因,它对我不起作用。

这是我类似的工作解决方案:

 string name = null; // Select the PropertyInfo of the column. PropertyInfo propertyInfo = query.First().GetType().GetProperty("first name"); if (propertyInfo != null) { try { // Select the content of the column. name = pi.GetValue(query.First(), null).ToString(); } catch (Exception) { // Continue with null-string. } 

}