我有以下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
的故障单。问题是,如果在我的过滤器中我将where
传递给Owner
,我会写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();
}
。看看我的过滤器:
{{1}}
答案 0 :(得分: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();
}
答案 1 :(得分:0)
使用select语句。
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();
答案 2 :(得分:0)
您可以将生成的查询投影到您喜欢的任何格式后过滤它。
使用此工作替换return语句还是有更复杂的要求我还没有完全理解?
return query.Select(t => new Ticket() {
Owner = t.Owner,
Dependency = t.Dependency;
}.ToList();