EF 多种查询方式

比较常用的查询方式linq to entity,这里先看一种写法:

   var query = (from d in testContext.Set<DepartPerson>()
                        //查询和sql很像,不过这里注意,查询多条件不是and
                         where 1 == 1 && 2 == 2 && 3 == 3
                         select new Dep_Person
                         {
                             Name = p.Name,
                             ID = p.ID
                         }).ToList()

当然还有另外一种写法,改用lambda表达式查询:

  var personIDList = testContext.Set<Person>().Where(p=>p.Name=="张三").Select(d=>new {ID=d.ID,Name=d.ID}).ToList();

实际应用中我们经常会碰到多表关联查询,以及多条件查询,下面看一下代码 怎么写:

  var query = (from d in testContext.Set<DepartPerson>()
                         join p in testContext.Set<Person>()
                         on new { id = d.PersonID, hosID = d.HospitalID } equals new { id = p.ID, hosID = "2" }
                         where 1 == 1 && 2 == 2 && 3 == 3
                         select new Dep_Person
                         {
                             Name = p.Name,
                             ID = p.ID,
                             DepID = d.ID,
                             HosID = d.HospitalID

                         }).ToList();

实际上也可以用lambda表达式

  var personIDList = testContext.Set<Person>().Where(p=>p.Name=="张三").Select(d=>new {ID=d.ID,Name=d.ID}).ToList();
             var list = testContext.Set<DepartPerson>().Where(d => personIDList.Contains(d.PersonID)).ToList();

还有一些操作,orderby 和groupby 这些和sql语句的很像,也容易理解,不再多说,这里说一下去重,官方提供的去重方法Distinct()是针对所有列去重,但是很多时候,如果我们想针对某一列去重,应该怎么做呢

方法一:利用groupby

var list = query.ToList().GroupBy(c => c.Name).Select(x => x.First()).ToList();

方法二:实现第三方扩展

 public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
        {

            HashSet<TKey> seenKeys = new HashSet<TKey>();
            foreach (TSource element in source)
            {
                if (seenKeys.Add(keySelector(element)))
                {
                    yield return element;
                }
            }
        }

方法二使用也很简单

 var query = (from d in testContext.Set<DepartPerson>()
                         join p in testContext.Set<Person>()
                         on new { id = d.PersonID, hosID = d.HospitalID } equals new { id = p.ID, hosID = "2" }
                         where 1 == 1 && 2 == 2 && 3 == 3
                         select new Dep_Person
                         {
                             Name = p.Name,
                             ID = p.ID,
                             DepID = d.ID,
                             HosID = d.HospitalID

                         }).DistinctByAll(c=>c.Name).ToList();

掌握了这些方法,日常得查询业务需求应该能满足了,当然如果你自己想自定义sql查询(拼接sql语句)可以这么做

        List<Dep_Person> peopleViews = testContext.Database.SqlQuery<Dep_Person>("SELECT Name, ID FROM Person").ToList();

这种方法注意的是,加入参数最好是格式化参数,不要直接拼接,以防sql注入

 

posted @ 2018-07-30 17:10  yaphetsfang  阅读(1166)  评论(0编辑  收藏  举报