Recently I worked on a project, which I started as code first and then I forced to switch to Database first. This post is about executing procedures from EF code first.(This is an update version of this post Here is my class structure and procedures.

class DatabaseContext : DbContext
{
public DbSet<Book> Books { get; set; }
public DbSet<Author> Authors { get; set; }
} class Book
{
public int Id { get; set; }
public string Name { get; set; }
public string ISBN { get; set; }
public int AuthorId { get; set; }
} class Author
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}

And here is my stored procedures

CREATE PROCEDURE usp_CreateBook
@BookName VARCHAR(200), @ISBN VARCHAR(200), @BookId INT OUTPUT
AS
SET NOCOUNT ON
INSERT INTO Books(Name, ISBN, AuthorId) VALUES(@BookName, @ISBN, 1)
SET @BookId = (SELECT SCOPE_IDENTITY()) CREATE PROCEDURE usp_CreateAuthor
@AuthorName VARCHAR(200), @Email VARCHAR(200) = NULL
AS
INSERT INTO Authors(Name, Email) VALUES(@AuthorName, @Email) CREATE PROCEDURE usp_GetAuthorByName
@AuthorName VARCHAR(200)
AS
SELECT [Id] ,[Name] ,[Email] FROM [Authors]
WHERE Name = @AuthorName

And you can execute using DbContext.Database class. The DbContext.Database.ExecuteSqlCommand() method helps to executes the given DDL/DML command against the database. And it will return the number of rows affected.

var affectedRows = context.Database.ExecuteSqlCommand("usp_CreateAuthor @AuthorName, @Email",
new SqlParameter("@AuthorName", "author"),
new SqlParameter("@Email", "email"));

Or you can use without creating the SqlParameters.

var affectedRows = context.Database.ExecuteSqlCommand
("usp_CreateAuthor @AuthorName = {0}, @Email= {1}",
"author", "email");

The DbContext.Database.SqlQuery method helps to return elements of the given generic type. The type can be any type that has properties that match the names of the columns returned from the query, or can be a simple primitive type.

var authors = context.Database.SqlQuery<Author>("usp_GetAuthorByName @AuthorName",
new SqlParameter("@AuthorName", "author"));

This method will return an DbRawSqlQuery, which you can enumerate using For / ForEach loop. For executing procedure with output parameter.

var bookIdParameter = new SqlParameter();
bookIdParameter.ParameterName = "@BookId";
bookIdParameter.Direction = ParameterDirection.Output;
bookIdParameter.SqlDbType = SqlDbType.Int;
var authors = context.Database.ExecuteSqlCommand("usp_CreateBook @BookName, @ISBN, @BookId OUT",
new SqlParameter("@BookName", "Book"),
new SqlParameter("@ISBN", "ISBN"),
bookIdParameter);
Console.WriteLine(bookIdParameter.Value);

Web API 2 Entity Framework 使用 Procedure的更多相关文章

  1. ASP.Net MVC-Web API使用Entity Framework时遇到Loop Reference

    原文地址:http://www.it165.net/pro/html/201210/3932.html 最近开始研究Web API,运气不错第一个测试项目就遇到问题@@-当新增Control时选择[A ...

  2. ASP.NET Web API系列教程目录

    ASP.NET Web API系列教程目录 Introduction:What's This New Web API?引子:新的Web API是什么? Chapter 1: Getting Start ...

  3. 【ASP.NET Web API教程】6.4 模型验证

    本文是Web API系列教程的第6.4小节 6.4 Model Validation 6.4 模型验证 摘自:http://www.asp.net/web-api/overview/formats-a ...

  4. 【ASP.NET Web API教程】2.3 与实体框架一起使用Web API

    原文:[ASP.NET Web API教程]2.3 与实体框架一起使用Web API 2.3 Using Web API with Entity Framework 2.3 与实体框架一起使用Web ...

  5. 【ASP.NET Web API教程】2 创建各种Web API

    原文 [ASP.NET Web API教程]2 创建各种Web API Chapter 2: Creating Web APIs第2章 创建各种Web API 本文引自:http://www.asp. ...

  6. Web API 2

    Asp.Net Web API 2 官网菜鸟学习系列导航[持续更新中]   前言 本来一直参见于微软官网进行学习的, 官网网址http://www.asp.net/web-api.出于自己想锻炼一下学 ...

  7. ASP.NET Web API系列教程(目录)(转)

    注:微软随ASP.NET MVC 4一起还发布了一个框架,叫做ASP.NET Web API.这是一个用来在.NET平台上建立HTTP服务的Web API框架,是微软的又一项令人振奋的技术.目前,国内 ...

  8. [转]Upgrading to Async with Entity Framework, MVC, OData AsyncEntitySetController, Kendo UI, Glimpse & Generic Unit of Work Repository Framework v2.0

    本文转自:http://www.tuicool.com/articles/BBVr6z Thanks to everyone for allowing us to give back to the . ...

  9. [转]Web API Introduction to OData Services using ASP.NET Web API

    本文转自:http://mahedee.net/tag/web-api/ What is OData? OData Stands for Open Data Protocol. It is a dat ...

随机推荐

  1. Hive学习之路 (一)Hive初识

    Hive 简介 什么是Hive 1.Hive 由 Facebook 实现并开源 2.是基于 Hadoop 的一个数据仓库工具 3.可以将结构化的数据映射为一张数据库表 4.并提供 HQL(Hive S ...

  2. mongo固定集合

    固定集合:事先创建,大小固定 类型于环形队列,空间不足队列头文件被替换 不能手动删除文档,只能自动替换 db.ceateCollection("COLLECTION_NAME",{ ...

  3. C# 下载文件

    最近一段时间,真的是太忙太忙了!经历了自我毕业以来最忙碌的一个项目! 说起这个项目,我有万千感慨 且不说技术能力,也无需谈论项目需求.单就项目压力,日常加班,周六日补班而言,我相信很多人是扛不住的! ...

  4. Jlink使用技巧之J-Scope虚拟示波器功能

    J-Link简介 J-Link是SEGGER公司为支持仿真ARM内核芯片推出的JTAG仿真器.简单地说,是给一个JTAG协议转换盒.其连接到计算机用的是USB接口,而到目标板内部用的还是jtag协议. ...

  5. Git 使用vi或vim命令打开、关闭、保存文件

    1 vi & vim 有两种工作模式: (1)命令模式:接受.执行 vi & vim 操作命令的模式,打开文件后的默认模式: (2)编辑模式:对打开的文件内容进行 增.删.改 操作模式 ...

  6. 一文看懂Transformer内部原理(含PyTorch实现)

    Transformer注解及PyTorch实现 原文:http://nlp.seas.harvard.edu/2018/04/03/attention.html 作者:Alexander Rush 转 ...

  7. xampp 使用过程中刚遇到的问题记录

    开始使用XAMPP的时候,都是可以正常连接的,但是过一段时间后,在用它创建表或其他操作,会报错,提示如下错误 Access denied for user ''@'localhost' to data ...

  8. 小P的字符串

    题目描述 小P最近在研究字符编码,给出一串由0.1组成的字符串,从中任意进行截取,如果截取的字符串对应一个英文字母的ASCII值,小P就把这个0.1串叫字母子串,问给定的字符串最多能截取出多少个字母子 ...

  9. ZOJ - 1610 经典线段树染色问题

    这个是一个经典线段树染色问题,不过题目给的是左右左右坐标,即[0,3]包含0-1这一段 1-2这一段 2-3这一段,和传统的染色不太一样,不过其实也不用太着急. 我们把左边的坐标+1,即可,那么[0, ...

  10. Linux安装Apache常见报错(二)

    配置Apache提示报错configure error: APR could not be located. Please use the --with-apr option. 解决办法: ./con ...