标签:
//遍历所有学生 DBSet using (var db = new Entities()) { foreach (var student in db.Student) { ObjectDumper.Write(student.StudentName); } };
说明:打印所有学生的姓名
using (var db = new Entities()) { //查询所有出生日期在1991年1月1日之后的学生 var day = Convert.ToDateTime("1991-1-1"); var students = from v in db.Student where v.Birthday >= day select v; foreach (var student in students) { ObjectDumper.Write(student.StudentName+"-"+student.Birthday); } };
执行结果:
此处注意:使用linq和lamba时,变量一定要提前转存,不能在linq内部使用C#函数。
错误的写法:
using (var db = new Entities()) { var students = from v in db.Student where v.Birthday >= Convert.ToDateTime("1991-1-1") select v; foreach (var student in students) { ObjectDumper.Write(student.StudentName+"-"+student.Birthday); } };
这样写直接就会报错:
using (var db = new Entities()) { var students = from v in db.Student orderby v.Birthday select v; foreach (var student in students) { ObjectDumper.Write(student); } };
降序:descending
var students = from v in db.Student orderby v.Birthday descending select v;
//find查询单个实体 using (var db = new Entities()) { var student = db.Student.Find(1); ObjectDumper.Write(student); };
说明:根据主键查询Student信息,如果找不到,则返回 NULL
//Single查询单个实体 using (var db = new Entities()) { var student = from v in db.Student where v.StudentName=="张三" select v; //single方法 查不到记录 或者 多条记录 都会报错 ObjectDumper.Write(student.Single()); };
说明:调用single方法查不到记录 或者 多条记录 都会报错
//SingleOrDefault查询单个实体 using (var db = new Entities()) { var student = from v in db.Student where v.StudentName == "李四" select v; //SingleOrDefault方法 查不到记录返回null ,如果查询到多条记录会报错 ObjectDumper.Write(student.SingleOrDefault()); };
说明:调用SingleOrDefault方法 查不到记录放回NULL 如果查询到多条记录报错
完整案例:
//遍历所有学生 using (var db = new Entities()) { var students = from v in db.Student select v; foreach (var student in students) { ObjectDumper.Write(student); } }; Console.WriteLine("==========按照生日排序==========="); //按照生日排序 升序 using (var db = new Entities()) { var students = from v in db.Student orderby v.Birthday descending select v; foreach (var student in students) { ObjectDumper.Write(student); } }; Console.WriteLine("==========find查询单个实体==========="); //find查询单个实体 using (var db = new Entities()) { var student = db.Student.Find(1); ObjectDumper.Write(student); }; Console.WriteLine("==========single查询单个实体==========="); //Single查询单个实体 using (var db = new Entities()) { var student = from v in db.Student where v.StudentName=="张三" select v; //single方法 查不到记录 或者 多条记录 都会报错 ObjectDumper.Write(student.Single()); }; Console.WriteLine("==========SingleOrDefault查询单个实体==========="); //SingleOrDefault查询单个实体 using (var db = new Entities()) { var student = from v in db.Student where v.StudentName == "李四" select v; //SingleOrDefault方法 查不到记录返回null ,如果查询到多条记录会报错 ObjectDumper.Write(student.SingleOrDefault()); };
【EF学习笔记05】----------DBContext基础查询
标签:
原文地址:http://www.cnblogs.com/gosky/p/5752001.html