I want to extend LINQ query based on some conditions.
Actually I am writing a dynamic search functionality where user can select any field and can search. Here if user selects a field that is not available in default LINQ query then I want to extend existing LINQ Query.
For Example
var query =
from tbl1 in context.Table1
join tbl2 in context.Table2 on tble1.Id equals tble2.tble1Id
where tble1.IsDeleted == false;
And If User Selects a field that cannot be searched in this above query then I want to extend "query" variable as below.
query = query
.GroupJoin(context.table3,
a => new { contactId = a.contact.Id, formId = a.contact.FormIdFK },
DynamicFieldData => new { contactId = DynamicFieldData.EntityIdFK, formId = DynamicFieldData.FormIdFK },
(x, y) => new { a = x, DynamicFieldData = y })
.SelectMany(x => x.DynamicFieldData.DefaultIfEmpty(),(x, y) => new { a = x.a, DynamicFieldData = y })
.AsQueryable();
And At the end I can apply dynamic Where Claus on above finalized query.
But when I try to assign updated query to "query" variable it says.
Errror: system.linq.iqueryable <some anonymous type 1 > cannot be implicitly converted to system.linq.iqueryable <some anonymous type 2 >
Usually I use the following pattern:
// apply join
var withOtherTable =
from q in query
join t in context.table3 on ... equals ... into gj
from t in gj.DefaultIfEmpty()
select new { q, t };
// apply filters
withOtherTable = withOtherTable.Where(x => x.t.SomeField == "some");
// back to original query
query = withOtherTable.Select(x => x.q);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.