简体   繁体   中英

Unable to Apply Linq Where Clause to Linked Entity in Entity Framework Core

I have a EventEntity which has IEnumerable<Poc> PocEntity .

public class EventEntity
{
    public Guid Id { get; set; }
    public IEnumerable<PocEntity> Poc { get; set; }
}

I'm trying to filter EventEntity based on PocEntity . So I'm trying like this,

IQueryable<EventEntity> query = _context.Events.Where(x => x.Poc.Where(p => p.PocId.Equals(pocId)));

But I'm getting error and I'm not able to achieve this. Please assist on how to do this. I'm using EF Core.

I'm getting two errors, Error 1:

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'bool'

Error 2:

Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type

The error is because the argument to your first Where() clause is the wrong type. x => x.Poc.Where(p => p.PocId.Equals(pocId)) needs to evaluate to a bool. To do this, you can use Any() instead of Where():

IQueryable<EventEntity> query = _context.Events.Where(x => x.Poc.Any(p => p.PocId.Equals(pocId)));

The problem is with the first where condition:

.Where(x => x.Poc.Where(p => p.PocId.Equals(pocId)));

The where clause expects a bool expression while the only thing it gets is a collection: p.PocId.Equals(pocId)

Solution : Just add Any() to the end of the collection as the following:

.Where(x => x.Poc.Where(p => p.PocId.Equals(pocId)).Any())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM