EF Linq包含许多关系

时间:2015-05-21 06:51:33

标签: c# linq entity-framework

我是LINQ的新手。我写了这段代码:

 public IEnumerable<Document> GetDocuments(string searchParam, int displayStart, int displayLenght, int sortColumnIndex, string searchDir, out int filteredDataCount, out int allDataCount)
        {
            using(var _db = new ApplicationDbContext())
            {
                var documents = _db.Documents.Where(x=>x.Deleted == null).Include(x=>x.VacationTypes);
                allDataCount = documents.Count();
                if (!String.IsNullOrEmpty(searchParam))
                {
                    documents = documents.Where(d => d.DocumentName.Contains(searchParam) || 
                        d.VacationTypes.Any(x=>x.Type.Contains(searchParam))).OrderBy(x=>x.DocumentName).ThenByDescending(d=>d.UploadDate);                    
                }
                filteredDataCount = documents.Count();
                if(sortColumnIndex == 0)
                {
                    switch (searchDir)
                    {
                        case "asc":
                            documents = documents.OrderBy(x => x.FileType).ThenByDescending(x => x.UploadDate).Skip(displayStart).Take(displayLenght);
                            break;
                        case "desc":
                            documents = documents.OrderByDescending(x => x.FileType).ThenByDescending(x => x.UploadDate).Skip(displayStart).Take(displayLenght);
                            break;
                    }

                }
                else if(sortColumnIndex == 1)
                {
                    switch (searchDir)
                    {
                        case "asc":
                            documents = documents.OrderBy(x => x.DocumentName).Skip(displayStart).Take(displayLenght);
                            break;
                        case "desc":
                            documents = documents.OrderByDescending(x => x.DocumentName).Skip(displayStart).Take(displayLenght);
                            break;
                    }

                }
                else if(sortColumnIndex == 2)
                {
                    switch(searchDir)
                    {
                        case "asc":
                            documents = documents.OrderByDescending(x => x.UploadDate).Skip(displayStart).Take(displayLenght);
                            break;
                        case "desc":
                            documents = documents.OrderBy(x => x.UploadDate).Skip(displayStart).Take(displayLenght);
                            break;
                    }
                }                
                return documents.ToList();
            }
        }

如您所见,我需要按DocumentNameVacationType过滤数据。文档与many-to-manyVacationTypes的关系。 VacationTypes有字段Type。我需要通过这个领域进行过滤。 问题:我的代码可以吗?任何人都可以提供更好的解决方案吗?

0 个答案:

没有答案