Help with linq request

I am trying to get some data, but I don’t know how to do it if in linq, here is how I am trying to do

from so in db.Operations
where ((opType!= "0" ? so.Operation == int.Parse(opType) : false) 
    && (idState!=0 ? so.State == idState : false) 
    && (start != null ? so.StartDate == start : false) 
    && (end !=null ? so.EndDate == end : false))
select so

Optip is Int, idState is Int, end is date-time, beginning is time

what am I trying to do, if they are not null, they add to the query function, so I can collect all the data

for example: in C # code

if((opType!= "0")
 where (so.Operation == int.Parse(opType)
if(idState!=0)
 where (so.Operation == int.Parse(opType) && so.State == idState
.......

so if it is not empty, this sentence in this sql query (TRUE part, I do not want to use the false part), add it to the place, so I can look for all parameters that are not null or 0

+3
source share
4 answers

Not sure what you want for sure, but here is an attempt:

var query = db.Operations.AsQueryable();

if (opType != null && opType != "0")
    query = query.Where(x => x.Operation == int.Parse(opType);

if (idState != 0) 
    query = query.Where(x => x.State == idState);

if (start != null) // assuming that start is of type DateTime? otherwise use DateTime.MinValue
    query = query.Where(x => x.StartDate.Date == start); // maybe >= is more appropriate

if (end != null) // also DateTime? assumed
    query = query.Where(x => x.EndDate.Date == end); // maybe <= is more appropriate

var result = query.ToList(); // e.g. could also do an foreach, depending what you want to do

, . , .ToList() foreach .

:

from so in db.Operations
where ((opType != null && opType!= "0" ? so.Operation == int.Parse(opType) : true) 
    && (idState!=0 ? so.State == idState : true) 
    && (start != null ? so.StartDate.Date == start : true) 
    && (end !=null ? so.EndDate.Date == end : true))
select so
0

&& ', , : true : false.

+1
opType!= "0" ? so.Operation == int.Parse(opType) : false

you should not use so.operation == int.parse .... instead use so.operation = int.Parse (opType)

0
source

You can use conditional parameters.

Edit:

where ((opType!= "0" ? so.Operation == int.Parse(opType) : false) 

To:

where ((opType!= "0" ? so.Operation == int.Parse(opType) : so.Operation == Operation) 

etc.

0
source

Source: https://habr.com/ru/post/1736027/


All Articles