使用LINQ查询查询数据库带来DTO列表的问题

时间:2016-08-14 21:18:06

标签: sql asp.net-mvc linq

我有以下格式的LINQ查询。问题是我以列表的形式传递了100 consumerID的列表。我想查询数据库并带来结果 所有这100个消费者。但是,查询只会为第一个人带来结果。我怀疑我在where子句中遗漏了一些东西。我确信所有这100个consumerIds数据库中都有匹配的结果。

public ICollection<ConsumerExchangeChangeDto> GetByConsumers(List<int> consumerIDs)
{
    EnrollmentReportingModel db = (EnrollmentReportingModel)Context.DbContext;
    var results = (from ecew in db.A
        join ecewe in db.B on ecew.ID 
        equals ecewe.ExchangeChangeEnrollmentWindowID into temp
        from j in temp.DefaultIfEmpty()
        join cecr in db.C on ecew.ConsumerExchangeChangeRequestID equals cecr.ID
        join con in db.D on cecr.ConsumerID equals con.ID
        where consumerIDs.Contains(con.ID) && !ecew.Deleted
        select new E
        {
            ConsumerID = con.ID,
            OrganizationID = con.OrganizationID,
            StartDate = ecew.StartDate,
            EndDate = ecew.EndDate,
            Deleted = ecew.Deleted
        }).ToList();
    return results;
}

这是dto类

public class E : ILzDto
{
  public int ConsumerID { get; set; }
  public int OrganizationID { get; set; }
  public DateTime? StartDate { get; set; }
  public DateTime? EndDate { get; set; }
  public bool Deleted { get; set; }
}

1 个答案:

答案 0 :(得分:1)

我认为你想要Any,而不是包含:

public ICollection<ConsumerExchangeChangeDto> GetByConsumers(List<int> consumerIDs)
{
    EnrollmentReportingModel db = (EnrollmentReportingModel)Context.DbContext;
    var results = (from ecew in db.A
        join ecewe in db.B on ecew.ID 
        equals ecewe.ExchangeChangeEnrollmentWindowID into temp
        from j in temp.DefaultIfEmpty()
        join cecr in db.C on ecew.ConsumerExchangeChangeRequestID equals cecr.ID
        where consumerIDs.Any(x => x == cecr.ConsumerID) && !ecew.Deleted
        select new E
        {
            ConsumerID = cecr.ConsumerID,
            OrganizationID = con.OrganizationID,
            StartDate = ecew.StartDate,
            EndDate = ecew.EndDate,
            Deleted = false 
        }).ToList();
    return results;
}