0

I am trying to insert if statement within Where in a model,

q = from vw_masterview in ctx.vw_MasterViews
where 
vw_masterview.LastDate <= toDate &&
vw_masterview.OfficeId == MemberRepository.AllowedOfficeId

AllowedOfficeId could be null, I would like to add if statment

q = from vw_masterview in ctx.vw_MasterViews
    where 
    vw_masterview.LastDate <= toDate &&
    ***if (MemberRepository.AllowedOfficeId != null)***
    vw_masterview.OfficeId == MemberRepository.AllowedOfficeId

Thanks in advance.

2 Answers 2

3

You can rewrite your query using the fluent notation and apply an additional Where statement when AllowedOfficeId isn't null:

var query = ctx.vw_MasterViews.Where(v => v.LastDate <= toDate);
if (MemberRepository.AllowedOfficeId != null)
{
    query = query.Where(v => v.OfficeId == MemberRepository.AllowedOfficeId);
}

Then you can either run the query or continue to build it up, such as using the Select method to retrieve specific properties or project into an anonymous type or new class.

0
2
q = from vw_masterview in ctx.vw_MasterViews
    where
        vw_masterview.LastDate <= toDate &&
        (
            (MemberRepository.AllowedOfficeId != null) &&
            (vw_masterview.OfficeId == MemberRepository.AllowedOfficeId)
        )
3
  • Thanks Chris, it worked well. I just found that I am using it again in the following: (Decimal)ctx.vw_MasterViews.Where(c => c.OfficeId == MemberRepository.AllowedOfficeId).Count(). I would appreciate your assistance
    – hncl
    Commented Nov 10, 2011 at 3:44
  • (Decimal) ctx.vw_MasterViews.Count(c => (MemberRepository.AllowedOfficeId != null) && (c.OfficeId == MemberRepository.AllowedOfficeId)) Commented Nov 10, 2011 at 4:58
  • Thanks Chris, I did not get any errors, however I get null value becasue I think the query still applying null value to AllowedOfficeId. What I am trying to do is to omitt AllowedOfficeId from where statement if it is null.
    – hncl
    Commented Nov 10, 2011 at 5:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.