Tengo una consulta LINQ y quiero pasarle parámetros de persona. Probablemente debería ser algo como esto.
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()
¿Cómo puedo hacerlo?
He usado IQueryble para reutilizar partes de consultas. Era algo como lo siguiente:
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));
Vanilla EF no permite este tipo de consultas. Sugeriría usar LINQKit . Solo necesita configurar DbContextOptions
:
builder .UseSqlServer(connectionString) .WithExpressionExpanding(); // enabling LINQKit extension
Entonces puedes usar tus expresiones de la siguiente manera:
var result = db.people .Select(x => new {PersonName = x.Name, EntityId = exp1.Invoke(x)}) .ToList()