0

I have the following linq query:

public static int GetContributions(PERSON person, DateTime startDate, DateTime endDate)
    {
        using (var db = new TestEntities())
        {
            var creditsSum = (from u in db.PERSON_SOCIAL_INSURANCE_CONTRIBUTIONS
                              where u.StartDate >= startDate
                              where u.EndDate <= endDate
                              where (u.PersonId == person.Id)
                              select (int?)u.NumOfContributions).Sum() ?? 0;

            return creditsSum;
        }
    }

I would like to create a similar method that returns the number of contributions that do not fall between the start and end date provided. So basically for it to return all entries that do not fall between startDate and endDate values.

Any help?

divega
  • 6,320
  • 1
  • 31
  • 31
Tommy
  • 445
  • 1
  • 6
  • 15

3 Answers3

1

AND all of your conditions together, put parentheses around them, and negate.

var creditsSum = (from u in db.PERSON_SOCIAL_INSURANCE_CONTRIBUTIONS
                          where !(u.StartDate >= startDate
                          && u.EndDate <= endDate)
                          where (u.PersonId == person.Id)
                          select (int?)u.NumOfContributions).Sum() ?? 0;
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
0

Change your conditions then:

var creditsSum = (from u in db.PERSON_SOCIAL_INSURANCE_CONTRIBUTIONS
                  where (u.StartDate > endDate || u.EndDate < startDate) &&
                        u.PersonId == person.Id
                  select (int?)u.NumOfContributions).Sum() ?? 0;

You don't need that many where statements, just use AND operator.

Ufuk Hacıoğulları
  • 37,978
  • 12
  • 114
  • 156
0

Your Where clause can looks like this:

b.PERSON_SOCIAL_INSURANCE_CONTRIBUTIONS
 .Where(
           (c => c.StartDate > endDate || c.EndDate < startDate)
           && u.PersonId == person.Id
       )
Hamlet Hakobyan
  • 32,965
  • 6
  • 52
  • 68