前面我们已经创建EDM、DbContext和实体类,接下来我们学习不同的查询实体方法,转变为数据库的SQL查询
Entity Framework支持3种查询方式:1)LINQ to Entities ,2)Entity SQL ,3)Native SQL
1.LINQ to Entities
Language-Integrated Query (LINQ)是一种强大的查询语言,在vs2008就引入。我们可以在c#或者vb中使用LINQ查询不同的数据源。LINQ-to-Entities运行在entity Framework中的实体上(与底层数据库关联)。你可以使用LINQ方法语法或者LINQ查询语法进行查询
LINQ Method syntax
//Querying with LINQ to Entities using (var context = new SchoolDBEntities()) { var L2EQuery = context.Students.where(s => s.StudentName == "Bill"); var student = L2EQuery.FirstOrDefault<Student>(); }
LINQ Query syntax:
using (var context = new SchoolDBEntities()) { var L2EQuery = from st in context.Students where st.StudentName == "Bill" select st; var student = L2EQuery.FirstOrDefault<Student>(); }
首先要创建context上下文对象,用using()初始化,因此当跳出作用域时,它会自动调用Dispose方法来释放DbContext。在上面的两种查询方法都会返回IQueryable
2.Entity SQL
另一种查询方式,它直接由Entityframework的Object Services操作,它返回ObjectQuery 代替IQueryable
你需要ObjectContext来创建查询语句
下面的代码段和上面的L2E查询一样
//Querying with Object Services and Entity SQL string sqlString = "SELECT VALUE st FROM SchoolDBEntities.Students " + "AS st WHERE st.StudentName == 'Bill'"; var objctx = (ctx as IObjectContextAdapter).ObjectContext; ObjectQuery<Student> student = objctx.CreateQuery<Student>(sqlString); Student newStudent = student.First<Student>();
你也可以使用EntityConnection 和 EntityCommand来执行Entity SQL
using (var con = new EntityConnection("name=SchoolDBEntities")) { con.Open(); EntityCommand cmd = con.CreateCommand(); cmd.CommandText = "SELECT VALUE st FROM SchoolDBEntities.Students as st where st.StudentName='Bill'"; Dictionary<int, string> dict = new Dictionary<int, string>(); using (EntityDataReader rdr = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.CloseConnection)) { while (rdr.Read()) { int a = rdr.GetInt32(0); var b = rdr.GetString(1); dict.Add(a, b); } } }
EntityDataReader不返回ObjectQuery,而是以行列的方式返回
3.Native SQL
你可以直接执行原生的SQL查询
using (var ctx = new SchoolDBEntities()) { var studentName = ctx.Students.SqlQuery("Select studentid, studentname, standardId from Student where studentname='Bill'").FirstOrDefault<Student>(); }