Linq to Entity : add filter to child entities of child entities

Here is my problem, this is now 1h I'm searching on web, can't find solution.

I have these classes :

public class User
{  
    public string Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Tipster> Tipsters { get; set; }
}

public class Tipster
{
    public string Id { get; set; }
    public string Name { get; set; }
    public bool Visible { get; set; }
    public virtual ICollection<Bet> Bets { get; set; }
}

public class Bet
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string State { get; set; }
    public virtual Tipster Tipster { get; set; }
}

So a User have a collection of Tipster that he's following, and tipsters can push bets, so they have collection of bets, and a bet have only one tipster that create it.

I'm working on WEB API, using Entity Framework, and I want using Linq to Entity to do this :

Get User by Id, including the collection of tipsters where visible == true, including bets they created but filtering these, with State = "pending".

I can filter the Tipsters Visible state, using .Any() or using

context.Entry(user).Collection( c => c.Tipsters ).Query(...)

But I don't know how to filter the child entities (bets) of my child entities (tipsters).


Try this. Might be more elegant ways to do it:

var result = (from user in users
                select new User
                {
                    Id = user.Id,
                    Name = user.Name,
                    Tipsters = user.Tipsters.Where(x => x.Visible).Select(y => new Tipster
                    {
                        Id = y.Id,
                        Name = y.Name,
                        Visible = y.Visible,
                        Bets = y.Bets.Where(z => z.State == "Pending").Select(b => new Bet
                        {
                            Id = b.Id,
                            Name = b.Name,
                            State = b.State
                        }).AsQueryable()
                    }).AsQueryable()
                }).AsQueryable();

Assuming the relations between tables are present:

var data=dbcontext.UserDataset.Include(u => u.Tipsters.Where(t => t.Visible));

should do the job

链接地址: http://www.djcxy.com/p/37658.html

上一篇: 将子对象添加到父项

下一篇: Linq to Entity:将过滤器添加到子实体的子实体