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. opencv中VideoCapture和cvCapture有什么区别?

    VideoCapture和cvCapture其实是一样的,你可以去看看源码,VideoCapture其实在内部调用了cvCapture.这是不同 版本的opencv导致的.我接触到的opencv有过一 ...

  2. 463. Island Perimeter Add to List

    You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represen ...

  3. 使用.NET中的XML注释(二) -- 创建帮助文档入门篇

    一.摘要 在本系列的第一篇文章介绍了.NET中XML注释的用途, 本篇文章将讲解如何使用XML注释生成与MSDN一样的帮助文件.主要介绍NDoc的继承者:SandCastle. 二.背景 要生成帮助文 ...

  4. angular +H5 上传图片 与预览图片

    //index.html <form class="form-horizontal"> <div class="panel panel-default& ...

  5. MySQL insert插入

    使用INSERT语句插入新数据 语法:INSERT [INTO] tbl_name [(col_name,...)] VALUES (pression,...),…      INSERT [INTO ...

  6. OpenWrt添加启动脚本

    1.在 /etc/init.d 目录下建立文件 vi silabs #!/bin/sh /etc/rc.common # Copyright (C) 2006 OpenWrt.org START=93 ...

  7. linux中普通用户修改密码出现(passwd:Authentication token manipulation error)

    如果在linux中,不管是root用户还是普通用户登录后,修改自己的密码,出现---passwd:Authentication token manipulation error---错误的解决办法: ...

  8. boost的asio接收单路大数据量udp包的方法

    开发windows客户端接收RTP视频流,当h264视频达到1080P 60fps的时候,按包来调用recvfrom的函数压力比较大,存在丢包的问题,windows的完成端口的性能效果当然可以解决这个 ...

  9. Fork/Join框架介绍

    转http://www.infoq.com/cn/articles/fork-join-introduction/ 1. 什么是Fork/Join框架 Fork/Join框架是Java7提供了的一个用 ...

  10. L2-022. 重排链表

    L2-022. 重排链表 时间限制 500 ms 内存限制 65536 kB 代码长度限制 8000 B 判题程序 Standard 作者 陈越 给定一个单链表 L1→L2→...→Ln-1→Ln,请 ...