如何使用表达式将 classProperty 传递给 LINQ

发布于 2025-01-16 05:29:05 字数 320 浏览 2 评论 0原文

我有一个 LINQ 查询,我想将 Person 参数传递给它。大概应该是这样的。

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

我该怎么做呢?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

仙气飘飘 2025-01-23 05:29:05

我使用 IQueryble 来重用部分查询。它类似于以下内容:

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

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));
俯瞰星空 2025-01-23 05:29:05

Vanilla EF 不允许此类查询。我建议使用 LINQKit。只需要配置DbContextOptions

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

然后您可以通过以下方式使用您的表达式:

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

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()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文