数据库のLINQ查询语句

14 篇文章 0 订阅



1.LINQ 查询简介

查询是一种从数据源检索数据的表达式。 查询通常用专门的查询语言来表示。 随着时间的推移,人们已经为各种数据源开发了不同的语言;例如,用于关系数据库的 SQL 和用于 XML 的 XQuery。 因此,开发人员对于他们必须支持的每种数据源或数据格式,都不得不学习一种新的查询语言。 LINQ 通过提供处理各种数据源和数据格式的数据的一致模型,简化了这一情况。

例子中主要以LINQ表达式为主,LINQ表达式结构更为清晰易于理解,同时也会给出对应的点标记写法(所有的LINQ查询表达式都可以转成对应的点标记。反之,不是所有的点标记都可以转成查询表达式。),所以如果想要了解这部分的读者也请往下看。本文会介绍LINQ查询表达式用法以及对应的Lambda表达式。



2.查询

在 C# 中可为以下对象编写 LINQ 查询:SQL Server 数据库、XML 文档、DO.NET 数据集以及支持 IEnumerable 或泛型 IEnumerable 接口的任何对象集合。

代码(但是我一般不这么写)

      int[] scores = new int[] { 97, 92, 81, 60 };

        // Define the query expression.
        IEnumerable<int> scoreQuery =
            from score in scores
            where score > 80
            select score;

        // Execute the query.
        foreach (int i in scoreQuery)
        {
            Console.Write(i + " ");
        }

使用 lambert表达式的方法:

class LINQQueryExpressions
{
    static void Main()
    {

        // Specify the data source.
        int[] scores = new int[] { 97, 92, 81, 60 };

        // Define the query expression.
        IEnumerable<int> scoreQuery =
            from score in scores
            where score > 80
            select score;

        // Execute the query.
        foreach (int i in scoreQuery)
        {
            Console.Write(i + " ");
        }
 }}
// Output: 97 92 81


3.筛选

AND 连接符:

where cust.City == "London" && cust.Name == "Devon"

OR 连接符:

where cust.City == "London" || cust.City == "Paris"


4.排序

正规写法

按照名字排序:

var queryLondonCustomers3 =
    from cust in customers
    where cust.City == "London"
    orderby cust.Name ascending
    select cust;
 //要对结果进行从 Z 到 A 的逆序排序,请使用 orderby…descending 子句。

以下示例对学生的姓氏进行主要排序,然后对其名字进行次要排序。

 IEnumerable<Student> sortedStudents =
            from student in students
            orderby student.Last ascending, student.First ascending
            select student;
lamber表达式写法
{
     List<Student> students = new List<Student>
        {
           new Student {First="Svetlana", Last="Omelchenko", ID=111},
           new Student {First="Claire", Last="O'Donnell", ID=112},
           new Student {First="Sven", Last="Mortensen", ID=113},
           new Student {First="Cesar", Last="Garcia", ID=114},
           new Student {First="Debra", Last="Garcia", ID=115}
        };
            var stu = students
            //升序的话就是自己的 OrderBy
                .OrderByDescending(x => x.ID)
                .ThenBy(x=>x.First)
                .ToList();
            foreach (var item in stu)
            {
                Console.WriteLine($"ID地址{item.ID} 名字{item.First}  姓{item.Last}");

            } }

5.分组

//按照年龄进行分组,查询相同年龄数量大于2的内容
 2 var res = from t in stu
 3     group t by t.Age into s
 4     where s.Count()>=2
 5     select s;
 6 //var res1 = stu.GroupBy(t => t.Age).Where(s => s.Count() >= 2);lambda表达式
 7 
  • 因为分组以后,只能对整个组的属性进行操作
  • 分组后,返回类型应该是一个数组,所以要把数组遍历出来,需要使用两个 foreach 语句
   List<Student> students = new List<Student>
        {
           new Student {First="Svetlana", Last="Omelchenko", ID=111,Score=80},
           new Student {First="Claire", Last="O'Donnell", ID=111,Score=200},
           new Student {First="Sven", Last="Mortensen", ID=111,Score=88},
           new Student {First="Cesar", Last="Garcia", ID=114,Score=26},
           new Student {First="Debra", Last="Garcia", ID=114,Score=98}
        };
            //按照ID 信息进行排名,并且把 人数大于2 的几组挑选出来
            var stu = students
               .GroupBy(x => x.ID)
               .Where(x => x.Count() >= 2)
               .ToList();

            foreach (var items in stu)
            {
                foreach (var item in items)
                {
                    Console.WriteLine($"ID地址{item.ID} 名字{item.First}  姓{item.Last}");
                }
            }

6.条件查询的包含

1.包含

 var stu = students
               .Where(x => x.First.Contains("C"))
               .ToList();

2.以什么开头

 .Where(x => x.First.StartsWith("a"))

3.以什么结尾

 .Where(x => x.First.EndsWith("a"))



7.非跟踪查询

跟踪行为决定了 Entity Framework Core 是否将有关实体实例的信息保留在其更改跟踪器中。 如果已跟踪某个实体,则该实体中检测到的任何更改都会在 SaveChanges() 期间永久保存到数据库。 EF Core 还将修复跟踪查询结果中的实体与更改跟踪器中的实体之间的导航属性

在只读方案中使用结果时,非跟踪查询十分有用。 可以更快速地执行非跟踪查询,因为无需设置更改跟踪信息。 如果不需要更新从数据库中检索到的实体,则应使用非跟踪查询。 可以将单个查询替换为非跟踪查询。

var blogs = context.Blogs
    .AsNoTracking()
    .ToList();


参考文献

[1] https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/concepts/linq/basic-linq-query-operations
[2 ]https://www.cnblogs.com/hellohxs/p/12266856.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值