Refactor Linq for Entity Framework

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
 
M

Miha Markic

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,
 
J

Johan Karlsson

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top