Как я пишу динамический запрос для Linq, если у меня есть сказать, класс Customer, который имеет поля:Динамический запрос в LINQ
string name
string address
int phoneno
я должен запроса на основе информации, предоставляемой аналогична
query = string.Empty;
if(!string.IsNullorEmpty(name))
{
query += "@name = name";
}
if(!string.IsNullorEmpty(address))
{
query += "@address = address";
}
if(!string.IsNullorEmpty(phoneno))
{
query += "@phoneno = phoneno";
}
var result = from condition in customer
where(query)
select condition;
Edit # 1:
детали изменчива во время выполнения, как
private Customer[] GetCustomers(Dictionary<string,string> attributes)
{
here the attribute may be, name alone, or name and address, or name address and phoneno
foreach(string field in attributes.key)
{
query += field == attributes[key];
}
Customers[] =ExecuteQuery(query);
}
Этот запрос поддерживается LINQ?
Edit # 2:
Привет Mouk,
Как я новичок в C#, я до сих пор изо всех сил, это не работает для меня.
var query = _ConfigFile.ConnectionMasterSection;
for(int i = 0; i < filter.count; i++)
{
query = result.Where(p => typeof(ConnectionMaster).GetProperty(filter[i].Attribute).Name == filter[i].Value);
}
Это yeilds Empty, где, как я использовал этот
var query = _ConfigFile.ConnectionMasterSection;
//Hard coded
res.Where(q => q.category == filter[0].Value);
И это сработало, как я ожидал.
Hi Bryan Watts,
Я также попробовал ваш код, и я получаю эту ошибку: «Lambda Parameter is not in scope».
for(int i = 0; i < filter.count; i++)
{
Field item = filter[i];
MemberExpression param = Expression.MakeMemberAccess(Expression.Parameter(typeof(Connection), "p"), typeof(Connection).GetProperty(item.Attribute));
MemberExpression constant = Expression.MakeMemberAccess(Expression.Constant(item), typeof(Field).GetProperty("Value"));
}
try
{
var myquery = Queryable.Where(coll, Expression.Lambda<Func<Connection, bool>>(
Expression.Equal(param, constant), Expression.Parameter(typeof(Connection),"p")));
}
Какая ошибка?
Добавлен пример моего ответа, который должен вести вас до конца. –