Home > Enterprise >  How to pass classProperty to LINQ using Expressions
How to pass classProperty to LINQ using Expressions

Time:03-24

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?

CodePudding user response:

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));

CodePudding user response:

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()
  • Related