MuriloKunze
MuriloKunze

Reputation: 15583

.Where in navigation properties

I have this model:

public class User
{
    //other properties
    public List<Task> Tasks {get;set;}
}

How can I select all properties of user and only Tasks with Date = DateTime.Today? Can I do this?

Upvotes: 0

Views: 52

Answers (1)

Slauma
Slauma

Reputation: 177133

var today = DateTime.Today;
var tomorrow = today.AddDays(1);

var users = context.Users
    .Select(u => new
    {
        User = u,
        Tasks = u.Tasks.Where(t => t.Date >= today && t.Date < tomorrow)
    })
    .AsEnumerable()
    .Select(a => a.User)
    .ToList();

This would populate the user.Tasks collection with the selected tasks automatically if the relationship is not many-to-many. If you only want another object (anonymous or some other non-entity class) with selected data from the user entity you can use:

var users = context.Users
    .Select(u => new    // or new SomeClass
    {
        Name = u.Name,
        // more properties
        Tasks = u.Tasks.Where(t => t.Date >= today && t.Date < tomorrow)
    })
    .ToList();

Upvotes: 1

Related Questions