简体   繁体   中英

How to refactor this linq query?

I have this below linq query of which 95% remains the same across 6 different scenarios.How can I refactor it so that I can write in one function and use it for all the cases?

var results = await (from r in Requests
                join ra in RequestAuthorisers
                    on cr.ID equals ra._REQUEST_ID
                where cr.FACILITY_ID == facilityId
                      && (r._REQUEST_STATUS_ID == RequestSubmitted || r._REQUEST_STATUS_ID == RequestPartiallyAuthorised )//check against more status codes based on different conditions
                      && ra.FACILITY_USER_ID == facilityUserId//don't check this if admin
                      && ra.AUTHORIZATION_DATE != null
                      && ra.REJECTION_DATE == null
                select new
                {
                    FacilityId = r.FACILITY_ID,
                    VersionId = r.VERSION_ID,
                    CreatedByTitle = r.CREATED_BY_USER_TITLE,
                    CreatedByFirstName = r.CREATED_BY_USER_FIRST_NAME,
                    CreatedByLastName = r.CREATED_BY_USER_LAST_NAME,
                    RequestDate = r.SUBMITTED_DATE,
                    RequestId = r.ID,
                    RequestType = r._TYPE_ID,
                    Status = r._REQUEST_STATUS_ID
                }).ToListAsync();

            var RequestResponse = results.Select(
                r => new RequestResponseDto
                {
                    FacilityId = r.FacilityId,
                    VersionId = r.VersionId,
                    CreatedByTitle = r.CreatedByTitle,
                    CreatedByFirstName = r.CreatedByFirstName,
                    CreatedByLastName = r.CreatedByLastName,
                    RequestDate = Convert.ToDateTime(r.RequestDate).ToString("s"),
                    RequestType = ((RequestType)r.RequestType).ToString(),
                    Status = ((RequestStatus)r.Status).ToString()
                }).ToList();

As you can the scenarios/queries differ only by if isAdmin and check against more status codes(as commented above), rest of the part becomes same.

I am using LINQ to EF(DB First). Thanks in advance.

Why not pass a boolean into the method:

public RequestResponseDto MyMethod(bool isAdmin, Status status)
{
    ...

    && 
    ((status == Status.Status1 && (r._REQUEST_STATUS_ID == RequestSubmitted || r._REQUEST_STATUS_ID == RequestPartiallyAuthorised))
    ||
    (status == Status.Status2 && (r._REQUEST_STATUS_ID == Something))
    ||
    (status == Status.Status3 && (r._REQUEST_STATUS_ID == SomethingElse || r._REQUEST_STATUS_ID == AnotherThing)))        

    ...

    && (isAdmin || ra.FACILITY_USER_ID == facilityUserId)

    ...
}

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