• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

173
Vistas
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 3 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

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 3 years ago · Santiago Trujillo Denunciar

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 3 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda