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. CodeForces - 688C:NP-Hard Problem (二分图&带权并查集)

    Recently, Pari and Arya did some research about NP-Hard problems and they found the minimum vertex c ...

  2. Broken Keyboard(模拟数组或者双重链表的运用)

    这题我是大写的服气,辛辛苦苦搞了个双重链表结果还一直不对,不对就算了,书上源代码打进去还是不对,我能怎么办我也很无奈.不过这题还是让我对双重链表更加了解和运用了!还是可以的! You’re typin ...

  3. Linux下系统监控工具nmon使用

    Mongodb安装在Centos7或以上的版本,对于系统的监控方法如下: 1.从\\10.10.10.1\ShareDoc\User\Zchen\linux系统监控下下载2个工具 nmon16e_mp ...

  4. 系列文章--Silverlight与WCF通信

    Silverlight与WCF通信(一) :Silverlight通过httpBinding访问IIS宿主WCF 摘要: 首语本人在学习Silverlight 和 WCF的时候,各种问题层出不穷,在园 ...

  5. as3设计模式乱用之工厂模式

    好久没写技术相关的日记了,一忙,二懒,三则被这单调的生活熏得没什么感悟. 其实这篇日记早就想写了,项目开发初期的时候,带学生.经常看到那种乱用设计模式的现象.一方面,公司面试人的时候喜欢问设计模式,另 ...

  6. inotify 同步脚本

    #!/bin/bash path1=/home/htoa/tomcat/webapps/ROOT/htoa/ ip=192.168.30.13 /usr/bin/inotifywait -mrq -- ...

  7. 5 Things You Should Know About the New Maxwell GPU Architecture

    The introduction this week of NVIDIA’s first-generation “Maxwell” GPUs is a very exciting moment for ...

  8. 容器中跨主机的网络方案-flannel

    容器中的网络是建立docker集群的重要内容. 本文将介绍如何用flannel实现容器的多节点互通. 下图是flannel的实现原理,摘自: http://docker-k8s-lab.readthe ...

  9. Boost.Asio基本原理(CSDN也有Markdown了,好开森)

    Boost.Asio基本原理 这一章涵盖了使用Boost.Asio时必须知道的一些事情.我们也将深入研究比同步编程更复杂.更有乐趣的异步编程. 网络API 这一部分包含了当使用Boost.Asio编写 ...

  10. How far away ?(LCA)dfs和倍增模版

    How far away ? Tarjan http://www.cnblogs.com/caiyishuai/p/8572859.html Time Limit: 2000/1000 MS (Jav ...