EF写distinct

在日常开发中常常是这么写的

 var logErrorRequest = from l in _logErrorRepository.Table
                                      select new
                                      {
                                          WrongTime = l.WrongTime,
                                          InstitutionlGuid = l.InstitutionlGuid,
                                          DataSource = l.DataSource,
                                          AccessionNumber = l.AccessionNumber,
                                          ServiceSectID = l.ExamineType,
                                          BusinessID = l.BusinessID
                                      };
                if (query.InstitutionGuid != null)
                {
                    logErrorRequest = logErrorRequest.Where(t => t.InstitutionlGuid == query.InstitutionGuid);
                }
                if (query.LastUpdateDateStart != null)
                {
                    logErrorRequest = logErrorRequest.Where(t => t.WrongTime >= query.LastUpdateDateStart);
                }
                if (query.LastUpdateDateEnd != null)
                {
                    logErrorRequest = logErrorRequest.Where(t => t.WrongTime <= query.LastUpdateDateEnd);
                }
                var result = logErrorRequest.Distinct();

但是实际上想要

Distinct的字段只有
 InstitutionlGuid,DataSource,AccessionNumber三个字段,可是如果只查询这三个的话下面的条件中的字段就会编译报错,为了只查询这三个字段并且还能使条件的字段可以使用,可以改造成如下写法:
    var logErrorRequest = from l in _logErrorRepository.Table
                                      select l;
                //直接写所有字段,这样就可以使用条件字段
                if (query.InstitutionGuid != null)
                {
                    logErrorRequest = logErrorRequest.Where(t => t.InstitutionlGuid == query.InstitutionGuid);
                }
                if (query.LastUpdateDateStart != null)
                {
                    logErrorRequest = logErrorRequest.Where(t => t.WrongTime >= query.LastUpdateDateStart);
                }
                if (query.LastUpdateDateEnd != null)
                {
                    logErrorRequest = logErrorRequest.Where(t => t.WrongTime <= query.LastUpdateDateEnd);
                }
                //在distinct的时候才会去查询,所以这里就可以select需要distinct的字段,然后再查询
                var result = logErrorRequest.Select(t=>new {t.InstitutionlGuid,t.DataSource,t.AccessionNumber }).Distinct();

 

 
posted @ 2017-08-23 18:56  洛晨随风  阅读(2625)  评论(0编辑  收藏  举报