I want to dynamically place column name in my select-query. How I can do this?
public IEnumerable MyTable MySelect(string colName, string param)
{
using (MyEnt
have you tried res.Field<string>(colName)
?
public IEnumerable MySelect(string colName, string param)
{
using (MyEntities db = new MyEntities ())
{
var query = from res in db.MyTable.AsEnumerable()
where res.Field<string>(colName).Contains(param)
select res;
return query;
}
}
Here is an example.
PS: I haven't compiled the code so might give error.
use Expression(Of Func(Of TableName, Boolean))
as input parameter to your method
Public Function SelectFirstOrDefault(ByVal filterExpr As Expression(Of Func(Of T, Boolean))) As T
Return _dbContext.Set(Of T).FirstOrDefault(filterExpr)
End Function
then you can call it as below:
Public Function Select() As MyTypeInfo
dim expr = New Expression(Of Func(Of TableNameClass, Object))() {Function(x) x.Code, Function(x) x.LastModifiedDate, Function(x) x.Title}
SelectFirstOrDefault(expr)
End Function
Using dynamic linq:
using System.Linq.Dynamic;
public IEnumerable MyTable MySelect(string colName, string param)
{
using (MyEntities db = new MyEntities ())
{
var query = db.MyTable.Where($"{colName} LIKE %{param}%");
return query;
}
}
Have a look at the Dynamic Linq library and ScottGu's how to library here - it allows for dynamic filtering, sorting etc.