Entity framework中LINQ的使用

一、linq和ef的差别

我们做项目时,难免会遇到用的不知道是啥,及把linq和EF搞混了。今天我带领大家梳理下思路,首先说linq查询,然后介绍EF查询

1.linq查询

  当我们使用linq查询时,转到定义会调到Queryable 类,  那么也就是说,这个类封装了linq所有查询的方法。

  IQeurable(IQuerable<T>)不会立即在内存里创建持久数据,只有遍历它(如通过foreach)、把它转换成List等情况下才会向内存加载数据,它可以实现“延期执行”,如果当前被加载的实体有关联实体,此关联实体可被接下来的访问加载。

2.EF查询

转到定义可以看到,所有EF查询方法都继承自DbSet类,提供了我们最常用的方法 :Add(TEntity entity),Remove(TEntity entity),Find(params object[] keyValues)

如果有主外键表相关操作时,用EF的find方法,其余能通用的都能通过,另外,返回值类型有所不同,linq两个方法返回的都是集合,find返回的是单个实体。但有一点是,它们都可以用var来接收.

 原文:https://www.cnblogs.com/shuai7boy/p/5347285.html

二、查询

1.简单查询

 

2.多表查询

 左链接

            DataClasses1DataContext db = new DataClasses1DataContext();
            var leftJoinSql = from student in db.Student
                              join book in db.Book on student.ID equals book.StudentID into temp
                              from tt in temp.DefaultIfEmpty()
                              select new
                              {
                                   sname= student.Name,
                                   bname = tt==null?"":tt.Name//这里主要第二个集合有可能为空。需要判断
                              };

 

3.高级查询

 
 public List<User> GetUsers(string companyID, string userName, int skip, int limit)
        {
            var dc = new DbContext();
            var query = (from c in dc.Users
                         join d in dc.UserRoles on c.Id equals d.UserId
                         join e in dc.Roles on d.RoleId equals e.Id
                         where c.CompanyId == companyID && c.IsDeleted == false && (string.IsNullOrWhiteSpace(userName) ? true : c.UserName.Contains(userName))
                         orderby c.Id
                         select new
                         {
                             Id = c.Id, 
                             UserName = c.UserName, 
                             RoleName = e.Name
                         }).Skip(skip).Take(limit).ToList()
                         .Select(x => new User
                         {
                             Id = x.Id, 
                             UserName = x.UserName, 
                             RoleName = x.RoleName
                         }).ToList();

            return query;
        }

这个查询是一个包含了条件过滤、分页、多表、转换为实体列表的综合查询,缺点是条件过滤无法动态化

LINQ to SQL语句学习系列文章推荐:https://kb.cnblogs.com/page/42465/

 4.group by

 from a in b

 group a by new {a.x} into aa

select new

{

 x = aa.Key.x

y = aa.Sum(s=>s.x)

}

 

 

 

 

三、LINQKit扩展

1. 判空扩展 - AndIf

public static class PredicateBuilderExtensions
    {
        public static Expression<Func<T, bool>> AndIf<T>(this ExpressionStarter<T> expr1, bool isExists, Expression<Func<T, bool>> expr2)
        {
            if (isExists)
            {
                return expr1.And(expr2);
            }

            return expr1;
        }
        public static Expression<Func<T, bool>> AndIf<T>(this Expression<Func<T, bool>> expr1, bool isExists, Expression<Func<T, bool>> expr2)
        {
            if (isExists)
            {
                return expr1.And(expr2);
            }

            return expr1;
        }
    }

具体使用

var predicate = PredicateBuilder.New<Order>();
predicate.Start(s => s.Date >= input.StartDate); 
predicate.AndIf(!input.No.IsNullOrWhiteSpace(), s => (s.No.Contains(input.No)));

附:

string的 IsNullOrWhiteSpace扩展

public static class StringExtensions
    {
        public static bool IsNullOrEmpty(this string str)
        {
            return string.IsNullOrEmpty(str);
        }
        
        public static bool IsNullOrWhiteSpace(this string str)
        {
            return string.IsNullOrWhiteSpace(str);
        }
    }

 

参考文章

https://www.cnblogs.com/xinjian/archive/2010/11/17/1879959.html

 

posted @ 2017-01-13 10:45  心存善念  阅读(676)  评论(0编辑  收藏  举报