Entity Framework Learning Series (5) - EF related queries

EDITORIAL


  • IEnumberable And IQueryable The difference?

    • IEnumberable Class call Skip and Take pre-loaded data expansion method has been re-local memory.

    • IQueryable Is the Skip and Take again after these methods expressions translated into SQL Server T-SQL statement to send commands, that is, the delay in loading data to really show when it is executed.

  • When will you use IQueryable and IEnumberable ?

    • Using the data access layer IQueryable , since data can be loaded into the business logic processing delay.

    • In many cases, the data access layer method calls the business layer is not required to immediately load the data from the database and then to memory.

    • If you need to use in the business layer lazy loading, we can put in the business layer IQueryable converted into IEnumberable load data out.

Note: wherein ToList () , FirstOrDefault () , INCLUDE () method may prohibit lazy loading.

First, the use Stopwatch query execution efficiency


In a statement Stopwatch () need to reference the object using System.Diagnostics;

//1.声明对象
Stopwatch st=new Stopwatch();
//2.开始
st.Start();
//
//3.执行代码
//

//4.结束
st.Stop();
//5.输出
Console.WriteLine("用时:{0}毫秒", st.ElapsedMilliseconds);

Second, a simple query


1.Linq writing:

static void SipleQuery_Linq()
{
    //依赖上下文对象
    using(DatabaseContext _db=new DatabaseContext())
    {
        //声明Stopwatch对象
        Stopwatch st=new Stopwatch();
        //执行开始
        st.Start();
        //Linq 简单查询
        //语法格式:from 变量 in 实体 select 变量;
        var result=from q  in _db.shippers
                   select q;
        //输出结果
        foreach(var item in result)
        {
            Console.WriteLine("供应商编号:" + item.ShipperId);
            Console.WriteLine("供应商名称:" + item.CompanyName);
            Console.WriteLine("联系电话:" + item.Phone);
            Console.WriteLine("---------------------------------");
        }
        //执行结束
        st.Stop();
        Console.WriteLine("用时:{0}毫秒", st.ElapsedMilliseconds);
        Console.ReadKey();
    }
}

2.Lambda written expression:

static void SipleQuery_lambda()
{
    //上下文依赖
    using(DatabaseContext _db=new DatabaseContext())
    {
        //声明Stopwatch
        Stopwacth st=new Stopwatch();
        //执行开始
        st.Start();
        //Lambda 写法
        var result =_db.shippers.ToList();
        //输出结果
        foreach(var item in result)
        {
            Console.WriteLine("供应商编号:" + item.ShipperId);
            Console.WriteLine("供应商名称:" + item.CompanyName);
            Console.WriteLine("联系电话:" + item.Phone);
            Console.WriteLine("---------------------------------");
        }
        //执行结束
        st.Stop();
        Console.WriteLine("用时:{0}毫秒", st.ElapsedMilliseconds);
        Console.ReadKey();
    }
}

Third, the conditions of inquiry


1.Linq wording

static void WhereQuery_Linq()
{   
    //声明上下文依赖
    using(DatabaseContext _db=new DatabaseContext())
    {
        //声明对象 需要引用 using System.Diagnostics;
        Stopwatch st=new Stopwatch();
        //执行开始
        st.Start();
        //linq 写法
        var result=from q in _db.shippers
                   where q.ShipperId==1
                   select q;
        //输出
        foreach (var item in result)
        {
            Console.WriteLine("供应商编号:" + item.ShipperId);
            Console.WriteLine("供应商名称:" + item.CompanyName);
            Console.WriteLine("联系电话:" + item.Phone);
            Console.WriteLine("---------------------------------");
        }
        //执行结束
        st.Stop();
        Console.WriteLine("用时:{0}毫秒", st.ElapsedMilliseconds);
        Console.ReadKey();
    }
}

2.lambda wording

static void WhereQuery_lambda()
{
    //上下文依赖对象
    using(DatabaseContext _db=new DatabaseContext())
    {
        //声明Stopwatch
        Stopwatch st=new Stopwatch();
        //执行开始
        st.Start();
        //lambda表达式
        var result=_db.shippers.Where<Shippers>(q=>q.ShipperId==1);
        //输出结果
        foreach (var item in result)
        {
            Console.WriteLine("供应商编号:" + item.ShipperId);
            Console.WriteLine("供应商名称:" + item.CompanyName);
            Console.WriteLine("联系电话:" + item.Phone);
            Console.WriteLine("---------------------------------");
        }
        //执行结束
        st.Stop();
        Console.WriteLine("用时:{0}毫秒", st.ElapsedMilliseconds);
        Console.ReadKey();
    }
}

Fourth, aggregate functions


1.Linq wording

static void Query_Linq()
{
    //上下文依赖
    using(DatabaseContext _db = new DatabaseContext())
    {
        //声明Stopwatch对象
        Stopwatch st = new Stopwatch();
        //执行开始
        st.Start();
        var linq_result_count = (from c in _db.shippers select c).Count();
        var linq_result_max = (from x in _db.shippers select x).Max(x => x.ShipperId);
        var linq_result_min = (from x in _db.shippers select x).Min(c => c.ShipperId);
        //执行结束
        st.Stop();
        //输出
        Console.WriteLine("总记录条数:", linq_result_count);
        Console.WriteLine("主键最大值:", linq_result_max);
        Console.WriteLine("主键最小值:", linq_result_min);
        Console.WriteLine("用时:{0}毫秒", st.ElapsedMilliseconds);
        Console.ReadKey();
    }
}

2.Lambda wording

static void Query_Lambda()
{
    //声明上下文
    using(DatabaseContext _db = new DatabaseContext())
    {
        //声明Stopwatch
        Stopwatch st = new Stopwatch();
        //执行开始
        st.Start();
        var result_count = _db.shippers.Count();
        var result_max = _db.shippers.Max(c => c.ShipperId);
        var result_min = _db.shippers.Min(c => c.ShipperId);
        //执行结束
        st.Stop();
        //输出
        Console.WriteLine("总记录条数:", linq_result_count);
        Console.WriteLine("主键最大值:", linq_result_max);
        Console.WriteLine("主键最小值:", linq_result_min);
        Console.WriteLine("用时:{0}毫秒", st.ElapsedMilliseconds);
        Console.ReadKey();
    }
}

Fifth, the connector


1.Linq wording

  • :( own syntax summary, do not like do not spray)
from 变量1 in 实体对象1
Join 变量2 in 实体对象2
on 变量1.字段 equals on 变量2.字段
select new{ 重新查询的字段 };
  • Specific examples
static void JoinQuery_Linq()
{
    //上下文依赖
    using(DatabaseContext _db=new DatabaseContext())
    {
        //声明Stopwatch
        Stopwatch st=new Stopwatch();
        //执行开始
        st.Start();
        var result=from a in _db.productus
                   join b in _db.shippers 
                   on a.SupplierId equals b.ShipperId
                   select new {
                        a.ProductId,
                        a.ProductName,
                        b.CompanyName
                   };
        foreach (var item in result)
        {
            Console.WriteLine("产品编号:" + item.ProductId);
            Console.WriteLine("产品名称:" + item.ProductName);
            Console.WriteLine("供应商名称:" + item.CompanyName);
            Console.WriteLine("---------------------------------");
        }
        //执行结束
        st.Stop();
        Console.WriteLine("用时:{0}毫秒", st.ElapsedMilliseconds);
        Console.ReadKey();
    }
}

2.Lambda Join wording

  • :( own syntax summary, do not like do not spray)
上下文对象.实体对象1.Join(实体对象2,
实体对象1 lambda 表达式,
实体对象2 lambda 表达式,
(实体1变量,实体2变量)=>new {需要查询的字段});
  • Specific examples
static void JoinQuery_Lambda()
{
    //上下文依赖
    using(DatabaseContext _db=new DatabaseContext())
    {
        //声明Stopwatch
        Stopwatch st=new Stopwatch();
        //执行开始
        st.Start();
        var result=_db.productus.Join(_db.shippers, p => p.SupplierId, s => s.ShipperId,  (p, s) => new {
            p.ProductId,
            p.ProductName,
            s.CompanyName
        });
        
        foreach (var item in result)
        {
            Console.WriteLine("产品编号:" + item.ProductId);
            Console.WriteLine("产品名称:" + item.ProductName);
            Console.WriteLine("供应商名称:" + item.CompanyName);
            Console.WriteLine("---------------------------------");
        }
        //执行结束
        st.Stop();
        Console.WriteLine("用时:{0}毫秒", st.ElapsedMilliseconds);
        Console.ReadKey();
    }
}

Sixth, the left outer join


1.Linq wording

Left outer join, it returns all elements in the first set, regardless of whether it is relevant elements in the second set.

In LINQ, the left outer join is performed by coupling the results of the packet call DefaultIfEmpty () method.

DefaultIfEmpty () method gets the specified element from the list. If the list is empty, the default value is returned.

static void LeftJoinQuery()
{
    //依赖上下文对象
    using(DatabaseContext _db=new DatabaseContext())
    {
        //声明Stopwatch
        Stopwatch st=new Stopwatch();
        //执行开始
        st.Start();
        var result=from a in _db.productus
                   join b in _db.shippers
                   on a.SupplierId equals b.ShipperId into GRP
                   from GRP2 in GRP.DefaultIfEmpty()
                   select new {a.ProductName, GRP = GRP2};
        foreach (var item in result)
        {
            Console.WriteLine("产品名称:" + item.ProductName);
            Console.WriteLine("---------------------------------");
            Console.WriteLine("供应商编号:" + item.GRP.ShipperId);
            Console.WriteLine("供应商名称:" + item.GRP.CompanyName);
            Console.WriteLine("联系电话:" + item.GRP.Phone);
            Console.WriteLine("---------------------------------");
        }
        //执行结束
        st.Stop();
        Console.WriteLine("用时:{0}毫秒", st.ElapsedMilliseconds);
        Console.ReadKey();
    }
}

2.Lambda wording

  • :( own syntax summary, do not like do not spray)
GroupJoin<TOuter,TInner,TKey,TResult>
(IEnumerable<TOuter>,            //要联接的第一个序列。
IEnumerable<TInner>,             //要与第一个序列联接的序列。
Func<TOuter,TKey>,               //用于从第一个序列的每个元素提取联接键的函数。
Func<TInner,TKey>,               //用于从第二个序列的每个元素提取联接键的函数。
Func<TOuter,IEnumerable<TInner>, //用于从第一个序列的元素和第二个序列的匹配元素集合中创建结果元素的函数。
TResult>);                       //结果元素的类型。

实体对象.GroupJoin(联接第一个实体,
第一个实体联接,
从第一个实体的每个元素提取联接键的函数,
(变量1,变量2)=> new {查询字段};
);
  • Specific examples
static void GroupJoinQuery()
{
    //上下文依赖
    using(DatabaseContext _db=new DatabaseContext())
    {
        //声明Stopwatch
        Stopwatch st=new Stopwatch();
        //执行开始
        st.Start();
        //实体1
        var mdl=_db.productus.ToList();
        //实体2
        var md2=_db.shippers.ToList();
        var result=mdl.GroupJoin(md2,a => a.SupplierId,cs => cs.ShipperId,(a, c) => new
                    {
                         pname = a.ProductName,
                         sname = c    
                    });
         foreach (var item in result)
         {
            Console.WriteLine($"{item.pname}");
            foreach (var items in item.sname)
            {
                Console.WriteLine($"{items.CompanyName}");
            }
         }
         //执行停止
         st.Stop();
         Console.WriteLine("用时:{0}毫秒", st.ElapsedMilliseconds);
         Console.ReadKey();
    }
}

Seven, sorting pagination


1.Linq wording

  • :( own syntax summary, do not like do not spray)
IQueryable<实体对象> 变量名称=(from (变量) in 上下文.实体对象 orderby 变量.字段 select (变量)).Skip(0).Take(10);

返回IQueryable<T>;
  • Specific examples
static void OrderByPageQuery()
{
    //上下文依赖
    using(DatabaseContext _db=new DatabaseContext())
    {
        //声明Stopwatch
        Stopwatch st=new Stopwatch();
        //执行开始
        st.Start();
        //查询前五条记录
        var result=(from q in _db.shippers
                   orderby q.ShipperId
                   select q).Skip(0).Take(5);
        //输出
        foreach (var item in result)
        {
            Console.WriteLine("供应商编号:" + item.ShipperId);
            Console.WriteLine("供应商名称:" + item.CompanyName);
            Console.WriteLine("联系电话:" + item.Phone);
            Console.WriteLine("---------------------------------");
        }
        //执行结束
        st.Stop();
        Console.WriteLine("用时:{0}毫秒", st.ElapsedMilliseconds);
        Console.ReadKey();
    }
}

2.Lambda wording

  • Syntax
IQueryable<T> (变量)=上下文对象.OrderBy(lambda表达式).Ship(0).Take(5);

返回IQueryable<T>;
  • Specific examples
static void OrderByPageQuery()
{
    //上下文依赖
    using(DatabaseContext _db=new DatabaseContext())
    {
        //声明Stopwatch
        Stopwatch st=new Stopwatch();
        //执行开始
        st.Start();
        //查询前五条记录
        var result=_db.shippers.OrderBy(c => c.ShipperId).Skip(0).Take(5);
        //输出
        foreach (var item in result)
        {
            Console.WriteLine("供应商编号:" + item.ShipperId);
            Console.WriteLine("供应商名称:" + item.CompanyName);
            Console.WriteLine("联系电话:" + item.Phone);
            Console.WriteLine("---------------------------------");
        }
        //执行结束
        st.Stop();
        Console.WriteLine("用时:{0}毫秒", st.ElapsedMilliseconds);
        Console.ReadKey();
    }
}

Learning is like rowing upstream. Continuous Learning ing ....

Guess you like

Origin www.cnblogs.com/ZengJiaLin/p/11515101.html