Querying with EDM:

We have created EDM, DbContext, and entity classes in the previous sections. Here, you will learn the different types of queries an entity framework supports, which is in turn converted into SQL query for the underlaying database.

Entity framework supports three types of queries: 1) LINQ to Entities, 2) Entity SQL, and 3) Native SQL

LINQ to Entities:

Language-Integrated Query (LINQ) is a powerful query language introduced in Visual Studio 2008. You can use LINQ in C# or Visual Basic to query different data sources. LINQ-to-Entities operates on entity framework entities to access the data from the underlying database. You can use LINQ method syntax or query syntax when querying with EDM. Visit LINQ Tutorials to learn LINQ step-by-step.

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>();
}

First, you have to create an object of context class, which is SchoolDBEntities. You should initialize it in using() so that once it goes out of scope then it will automatically call Dispose() method of DbContext. In both the syntaxes above, context returns IQueryable.

Learn different types of LINQ to Entities projection query in the Projection Query section.

Entity SQL:

Entity SQL is another way to create a query. It is processed by the Entity Framework’s Object Services directly. It returns ObjectQuery instead of IQueryable.

You need ObjectContext to create a query using Entity SQL.

The following code snippet shows the same query result as L2E query above.

//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>();

You can also use EntityConnection and EntityCommand to execute Entity SQL as shown below:

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();
var b = rdr.GetString();
dict.Add(a, b);
}
}
}

EntityDataReader doesn't return ObjectQuery. Instead, it returns the data in rows & columns.

Visit MSDN blog to learn Entity SQL.

Native SQL:

You can execute native SQL queries for a relational database as shown below:

using (var ctx = new SchoolDBEntities())
{
var studentName = ctx.Students.SqlQuery("Select studentid, studentname, standardId from Student where studentname='Bill'").FirstOrDefault<Student>();
}

Learn to execute raw sql query using DbContext in Raw SQL Query section.

Entity Framework Tutorial Basics(15):Querying with EDM的更多相关文章

  1. Entity Framework Tutorial Basics(1):Introduction

    以下系列文章为Entity Framework Turial Basics系列 http://www.entityframeworktutorial.net/EntityFramework5/enti ...

  2. Entity Framework Tutorial Basics(4):Setup Entity Framework Environment

    Setup Entity Framework Environment: Entity Framework 5.0 API was distributed in two places, in NuGet ...

  3. Entity Framework Tutorial Basics(43):Download Sample Project

    Download Sample Project: Download sample project for basic Entity Framework tutorials. Sample projec ...

  4. Entity Framework Tutorial Basics(42):Colored Entity

    Colored Entity in Entity Framework 5.0 You can change the color of an entity in the designer so that ...

  5. Entity Framework Tutorial Basics(41):Multiple Diagrams

    Multiple Diagrams in Entity Framework 5.0 Visual Studio 2012 provides a facility to split the design ...

  6. Entity Framework Tutorial Basics(37):Lazy Loading

    Lazy Loading: One of the important functions of Entity Framework is lazy loading. Lazy loading means ...

  7. Entity Framework Tutorial Basics(36):Eager Loading

    Eager Loading: Eager loading is the process whereby a query for one type of entity also loads relate ...

  8. Entity Framework Tutorial Basics(34):Table-Valued Function

    Table-Valued Function in Entity Framework 5.0 Entity Framework 5.0 supports Table-valued functions o ...

  9. Entity Framework Tutorial Basics(33):Spatial Data type support in Entity Framework 5.0

    Spatial Data type support in Entity Framework 5.0 MS SQL Server 2008 introduced two spatial data typ ...

随机推荐

  1. 加密算法之BLOWFISH算法

    加密信息 BlowFish算法用来加密64Bit长度的字符串. BlowFish算法使用两个"盒"--ungignedlongpbox[18]和unsignedlongsbox[4 ...

  2. C程序设计语言阅读笔记

    预处理器 ->.i  编译器 >.s 汇编器 >.o 链接器  --可执行文件   ------------------ math.h头文件包含各种数学函数的声明,所有函数都返回一个 ...

  3. Express+Mongoose(MongoDB)+Vue2全栈微信商城项目全记录(一)

    最近用vue2做了一个微信商城项目,因为做的比较仓促,所以一边写一下整个流程,一边稍做优化. 项目github地址:https://github.com/seven9115/vue-fullstack ...

  4. bzoj 4299 Codechef FRBSUM

    定义一个集合的神秘数为不能表示成这个集合的某个子集和的最小正整数,给一个数列,多次求区间神秘数 $n \leq 100000$ sol: 考虑这个神秘数的性质,可以发现,如果神秘数是 $x$,那么 $ ...

  5. Swap Adjacent Elements

    You have an array a consisting of n integers. Each integer from 1 to n appears exactly once in this ...

  6. AtCoder Beginner Contest 087 D - People on a Line

    Time limit : 2sec / Memory limit : 256MB Score : 400 points Problem Statement There are N people sta ...

  7. Audiophobia(Floyd算法)

    个人心得:这在一定途径上完成查询方面还是很吃力,得多锻炼空间能力,不能再每次都看到就后退,要全力应对, 那怕被虐的不要不要的. 这题主要是求俩个端点中所有路径中最大构成的集合中最小的数值,其实开始思想 ...

  8. [Luogu4177][CEOI2008]order

    luogu sol 这题有点像网络流24题里面的太空飞行计划啊. 最大收益=总收益-最小损失. 先令\(ans=\sum\)任务收益. 源点向每个任务连容量为收益的边. 每个机器向汇点连容量为购买费用 ...

  9. 在装有windows跟ubuntu的机器上重新安装windows后修复ubuntu的grub

    本文只对没有单独用类似easyBCD这种软件单独设立启动分区的双系统,在重新安装win7之后,因为win7覆盖了ubuntu的grub,导致ubuntu无法启动的问题. (1)不管使用什么方法,首先需 ...

  10. Linux基础命令-系统时间

    Linux启动时从硬件读取日期和时间信息,读取完成以后,就不再与硬件相关联 Linux的两种时钟 系统时钟:由Linux内核通过CPU的工作频率进行的: date:显示系统时间 +%D +%F dat ...