And*_*ndy 12 c# string entity field
我正在寻找获得这样的东西的方法:
string _col1 = "first name";
string _name;
var query = from c in ctx.Customers select c;
_name = query.FirstOrDefault().[_name];
Run Code Online (Sandbox Code Playgroud)
据我所知,我只能获得强类型字段名称,但我想将它们作为字符串变量提供.
Ric*_*ith 20
我不确定EF是否为您提供了根据属性的字符串名称获取属性值的方法,但您可以使用反射.
string name = typeof(Customer)
.GetProperty("first name")
.GetValue(query.First(), null) as string;
Run Code Online (Sandbox Code Playgroud)
我猜你正在处理的EF课被称为Customer.
你需要使用反射.如果您尝试按动态选择的列进行过滤,则可以尝试以下方法:
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<Func<YourType, bool>> lambda =
Expression.Lambda<Func<YourType, bool>>(containsMethod, parameter);
var companies = repository.AsQueryable().Where(lambda);
Run Code Online (Sandbox Code Playgroud)
我你要做的是选择一个特定的列,然后你可以使用相同的原理生成lamba表达式并在select中使用它(减去条件)
var companies = repository.AsQueryable().Where(whatever).Select(lambda);
Run Code Online (Sandbox Code Playgroud)