Execute Native SQL Query

You can execute native raw SQL query against the database using DBContext. You can execute the following types of queries:

  1. SQL query for entity types which returns particular types of entities
  2. SQL query for non-entity types which returns a primitive data type
  3. Raw SQL commands to the database

SQL query for entity types:

As we have seen in one of the previous chapters, DBSet has SQLQuery() method to write raw SQL queries which return entity instances. The returned objects will be tracked by the context, just as they would be if they were returned by a LINQ query. For example:

using (var ctx = new SchoolDBEntities())
{
var studentList = ctx.Students.SqlQuery("Select * from Student").ToList<Student>(); }

However, columns returned by SQL query should match the property of an entity type of DBSet otherwise, it will throw an exception. For example:

using (var ctx = new  SchoolDBEntities())
{
var studentName = ctx.Students.SqlQuery("Select studentid, studentname
from Student where studentname='New Student1'").ToList(); }

If you change the column name in query, then it will throw an exception because it must match column names:

using (var ctx = new SchoolDBEntities())
{
//this will throw an exception
var studentName = ctx.Students.SqlQuery("Select studentid as id, studentname as name
from Student where studentname='New Student1'").ToList();
}

SQL query for non-entity types:

A SQL query returning instances of any type, including primitive types, can be created using the SqlQuery method on the Database class. For example:

using (var ctx = new SchoolDBEntities())
{
//Get student name of string type
string studentName = ctx.Database.SqlQuery<string>("Select studentname
from Student where studentid=").FirstOrDefault<string>();
}

Raw SQL commands to the database:

ExecuteSqlCommnad method is useful in sending non-query commands to the database, such as the Insert, Update or Delete command. For example:

using (var ctx = new SchoolDBEntities())
{ //Update command
int noOfRowUpdated = ctx.Database.ExecuteSqlCommand("Update student
set studentname ='changed student by command' where studentid=");
//Insert command
int noOfRowInserted = ctx.Database.ExecuteSqlCommand("insert into student(studentname)
values('New Student')");
//Delete command
int noOfRowDeleted = ctx.Database.ExecuteSqlCommand("delete from student
where studentid="); }

Entity Framework Tutorial Basics(39):Raw SQL Query的更多相关文章

  1. Entity Framework Tutorial Basics(15):Querying with EDM

    Querying with EDM: We have created EDM, DbContext, and entity classes in the previous sections. Here ...

  2. Entity Framework Tutorial Basics(1):Introduction

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

  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(17):DBSet Class

    DBSet Class DBSet class represents an entity set that is used for create, read, update, and delete o ...

  5. 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 ...

  6. 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 ...

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

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

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

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

  9. 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 ...

随机推荐

  1. POJ - 2079:Triangle (旋转卡壳,求最大三角形)

    Given n distinct points on a plane, your task is to find the triangle that have the maximum area, wh ...

  2. leetcode_sql_1,176,177

    1.176题目,Second Highest Salary,https://leetcode.com/problems/second-highest-salary/#/description Writ ...

  3. Django ImageField 上传图片并保存到数据库

    转自:http://logic0.blog.163.com/blog/static/188928146201371235435974/ Form代码: class ImageUploadForm(fo ...

  4. [独孤九剑]Oracle知识点梳理(二)数据库的连接

    本系列链接导航: [独孤九剑]Oracle知识点梳理(一)表空间.用户 [独孤九剑]Oracle知识点梳理(二)数据库的连接 [独孤九剑]Oracle知识点梳理(三)导入.导出 [独孤九剑]Oracl ...

  5. linux 内核移植和根文件系统的制作【转载】

    原文地址:http://www.cnblogs.com/hnrainll/archive/2011/06/09/2076214.html 1.1 Linux内核基础知识 在动手进行Linux内核移植之 ...

  6. h5 离线缓存小demo

    传统的web应用是在线应用,这其实也是web的特色,对于PC时代问题并不大,但到了移动互联网时代,设备终端位置不再固定,依赖无线信号,网络的可靠性变得更低.比如:在火车上,穿山越岭进隧道,便无法访问w ...

  7. ArcGis教程

    91卫图助手帮助中心-如何导出ArcGIS Server瓦片格式并进行发布 http://help.91weitu.com/rhdcarcgis%20serverwpgsbjxfb.html ArcG ...

  8. 蓝桥杯 算法训练 ALGO-143 字符串变换

    算法训练 字符串变换   时间限制:1.0s   内存限制:256.0MB 问题描述 相信经过这个学期的编程训练,大家对于字符串的操作已经掌握的相当熟练了.今天,徐老师想测试一下大家对于字符串操作的掌 ...

  9. RabbitMQ 基本概念和使用

    当前各种应用大量使用异步消息模型,并随之产生众多消息中间件产品及协议,标准的不一致使应用与中间件之间的耦合限制产品的选择,并增加维护成本.AMQP是一个提供统一消息服务的应用层标准协议,基于此协议的客 ...

  10. [转]ubuntu 网络配置 作者:Yudar

    检查网络配置命令:ifconfig 一.通过配置文件配置 新手没怎么用过Ubuntu,所以走了不少弯路,网上找了很多方法,大都没对我起到帮助作用,所以把自己的配置方法写一写. Ubuntu上连了两块网 ...