AnonyMouse
AnonyMouse

Reputation: 18630

Linq query to find items that could be within a range

I have an object Invoice which belongs to an Area:

public class Invoice : IEntity, IValidatableObject
    {
            ...

        public virtual int? AreaId { get; set; }
            ...
        // Navigation properties
        public virtual Area Area { get; set; }
            ...
    }

I also have a User object which can belong to multiple areas:

public class User : IEntity, INamedType
    {
        ...

        //Navigation properties
        public virtual ICollection<Area> Areas { get; set; }

        ...
    }

What I'm wanting to achieve is to get for a user all the invoices that belong to any of their areas. I tried writing it but it's not even close to right:

var invoices = _db.Invoices.Where(x => x.AreaId == user.Areas.Contains(z => z.Id));

Can anyone help me with this query?

Upvotes: 0

Views: 85

Answers (2)

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

I think something like that should work:

var invoices = _db.Invoices.Where(x => user.Areas.Any(z => z.ID == x.AreaId))

Upvotes: 0

Juan Ayala
Juan Ayala

Reputation: 3518

var invoices = _db.Invoices.Where(x =>  user.Areas.Any(z => z.Id == x.AreaId));

Upvotes: 1

Related Questions