0

我有以下 POCO:

public Ticket
{
    public int Id { get; set; }
    public int IdOwner { get; set; }
    public int IdDependency { get; set; }
    public string SerialNumber { get; set; }

    public Owner Owner { get; set; } 
    public Dependency Dependency { get; set; }
}

public Owner 
{
    public int Id { get; set; }
    public string Name { get; set; }
    // Other attributes
}

public Dependency 
{
    public int Id { get; set; }
    public string Name { get; set; }
    // Other attributes
}

我想退回一张List只有Owner Name和的门票Dependency Name。问题是,我会写一个whereifOwner在我的过滤器中我通过OwnerId, 和相同的Dependency. 查看我的过滤器:

public List<Ticket> SelectTickets(string SerialNumber, int IdOwner, int IdDependency)
{
    IQueryble<Ticket> query = context.Tickets.Where(t => t.SerialNumber == SerialNumber);

    if (IdOwner != 0)
    {
        query = query.Where( ?? );
    }

    if (IdDependency!= 0)
    {
        query = query.Where( ?? );
    }

    return query.ToList();
}
4

3 回答 3

0

这将是有道理的,如果我明白你的意思。

        public Ticket
        {
            public int Id { get; set; }
            public int OwnerId{ get; set; }
            public int DependencyId { get; set; }
            public string SerialNumber { get; set; }

            public Owner Owner { get; set; } 
            public Dependency Dependency { get; set; }
        }

        public Owner 
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public List<Ticket> Tickets {get;set;}
        }

        public Dependency 
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public List<Ticket> Tickets {get;set;}
        }
        public List<Ticket> SelectTickets(string serialNumber, int ownerId, int dependencyId)
        {
            return context.Tickets.Where(t => t.SerialNumber == serialNumber && t.OwnerId == ownerId && t.DependencyId == dependencyId).ToList();
        }
于 2012-04-20T14:08:42.007 回答
0

使用选择语句。

query = query.Select(t => new Ticket { 
    Owner = new Owner {Name = t.Owner.Name}, 
    Dependency = new Dependency  {Name = t.Dependency.Name}
}); 
return query.ToList();

但是,在这种情况下,您似乎不想返回 Ticket 而是返回一些其他对象,例如 TicketSummary

public class TicketSummary {
    public OwnerName {get;set;}
    public DependencyName {get;set;}
}

那么你会有

query = query.Select(t => new TicketSummary { 
    OwnerName = t.Owner.Name, 
    DependencyName = t.Dependency.Name
}); 
return query.ToList();
于 2012-04-20T14:09:01.310 回答
0

您可以在过滤后将生成的查询投影为您喜欢的任何格式。

用这个替换return语句对你有用还是你有更复杂的要求我不完全理解?

return query.Select(t => new Ticket() {
    Owner = t.Owner,
    Dependency = t.Dependency;
}.ToList();
于 2012-04-20T14:11:15.357 回答