如何使用 Linq to Entities 对查询进行分区并仅加载几个属性

本文关键字:加载 属性 几个 分区 to Linq 何使用 Entities 查询 | 更新日期: 2023-09-27 18:31:57

我有以下 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
}

我想退回只有Owner NameDependency NameList票。问题是,如果我在过滤器中传递了OwnerId,我将用Owner编写一个where,并且对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();
}

如何使用 Linq to Entities 对查询进行分区并仅加载几个属性

如果我理解你的意思,那将是有道理的。

        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();
        }

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

用这个替换 return 语句是否适合您,或者您是否有我没有完全理解的更复杂的要求?

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

使用 select 语句。

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

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

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();