简体   繁体   中英

linq predicate in c#

i have two tables(for Ex:TableEmployee,TableSal) with no relationship, and i have to write predicate using these two tables,

TableEmployees:This table contains Name, DepartmentId columns

TableSal: this table contains Name,DepartmentId,TotalSal

Question: i have to write predicate for "is DepartmentId in TableSal Matches with any DepartmentId in TableEmployees"

i've tried these methods but getting erors,

Method1:

predicate = predicate.And(
      n => context.Tbl_Sal
        .Where(d => d.DepartmentId.HasValue)
        .Select(i => i.DepartmentId)
        .Equals(n.DepartmentId)
      );

Method2:

predicate = predicate.And(
   n => context.Tbl_Sal
      .Where(d => d.DepartmentId.HasValue)
      .ToList().Find(d => d.DepartmentId == n.DepartmentId) != null);

How can i write Predicate.... for this situation....

I wonder why you're dealing with raw expressions. Using linq, you could do:

var query = context.TableSal
           .Where(d => context.TableEmployees.Where(e => e.DepartmentId.HasValue)
                      .Select(e => e.DepartmentId)
                      .Contains(d.DepartmentId));

which gives you all TableSal records of which DepartmentId is in the DepartmentId s of TableEmployees .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM