Refactor Linq for Entity Framework

  • Thread starter Thread starter Johan Karlsson
  • Start date Start date
J

Johan Karlsson

Hi!

I'm new to both Linq and Entity Framework and I have a simple question based
on a code example.

Given the query below

var query = from c in context.Customers
where c.Roles.Any( e => e.User.Id == userId ) &&
c.SomeOtherProperty == SomeOtherValue
select c;

Is it possible to refactor out part of the where clause for security
reasons, so you don't end up with a bunch of different places that could
over time differ?

Something like

var query = from c in context.Customers
where BuildSecurityExpression() &&
c.SomeOtherProperty == SomeOtherValue
select c;

Thanks

// Johan
 
Hi Johan,

Yes, you can.
Try this:
Expression<Func<Customer, bool>> condition = c => c.Roles.Any( e =>
e.User.Id == userId );
var query = from c in context.Customers.Where(condition)
where c.SomeOtherProperty == SomeOtherValue
select c;

HTH,
 
Hi!

Thank you for your reply! It worked perfectly!

// Johan

Miha Markic said:
Hi Johan,

Yes, you can.
Try this:
Expression<Func<Customer, bool>> condition = c => c.Roles.Any( e =>
e.User.Id == userId );
var query = from c in context.Customers.Where(condition)
where c.SomeOtherProperty == SomeOtherValue
select c;

HTH,
--
Miha Markic [MVP C#, INETA Country Leader for Slovenia]
RightHand .NET consulting & development www.rthand.com
Blog: blog.rthand.com

Johan Karlsson said:
Hi!

I'm new to both Linq and Entity Framework and I have a simple question
based on a code example.

Given the query below

var query = from c in context.Customers
where c.Roles.Any( e => e.User.Id == userId ) &&
c.SomeOtherProperty == SomeOtherValue
select c;

Is it possible to refactor out part of the where clause for security
reasons, so you don't end up with a bunch of different places that could
over time differ?

Something like

var query = from c in context.Customers
where BuildSecurityExpression() &&
c.SomeOtherProperty == SomeOtherValue
select c;

Thanks

// Johan
 
Back
Top