Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

225
Views
How to pass classProperty to LINQ using Expressions

I have a LINQ query, and I want to pass Person parameters to it. Probably it should be something like this.

Expression<Func<Person, long>> exp1 = person.CarId;
Expression<Func<Person, long>> exp2 = person.PetId;

var result = db.people.Select(x => new {PersonName = x.Name, EntityId = exp1}).ToList()
            

How can I do it?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

I've used IQueryble to reuse parts of queries. It was something like the following:

var withPets = Get(GetWithPetId);
                
List<WithEntityId> Get(Func<IQueryable<Person>, IQueryable<WithEntityId>> transformer)
{
    transformer(db.People.Where(...))
        .Where( x => x.EntityId > 100)
        .ToList(); 
}

IQueryable<WithEntityId> GetWithPetId(IQueryable<Person> people)
    => people.Select(x => new WithEntityId(x.Name, x.PetId));

IQueryable<WithEntityId> GetWithCard(IQueryable<Person> people)
    => people.Select(x => new WithEntityId(x.Name, x.CarId));
over 4 years ago · Santiago Trujillo Report

0

Vanilla EF do not allow such queries. I would suggest to use LINQKit. It needs just configuring DbContextOptions:

builder
    .UseSqlServer(connectionString)
    .WithExpressionExpanding(); // enabling LINQKit extension

Then you can use your expressions in the following way:

var result = db.people
   .Select(x => new {PersonName = x.Name, EntityId = exp1.Invoke(x)})
   .ToList()
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!