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. Maven项目运行Junit测试用例 出现ClassNotFound

    Maven 打包命令 clean package 会清空target下的目录 包含 test-classes 目录 这样执行junit的时候,会出现 ClassNotFound的错误 执行下面的命令即 ...

  2. Python股票分析系列——自动获取标普500股票列表.p5

    该系列视频已经搬运至bilibili: 点击查看 欢迎来到Python for Finance教程系列的第5部分.在本教程和接下来的几节中,我们将着手研究如何为更多公司提供大量的定价信息,以及如何一次 ...

  3. 朱晔和你聊Spring系列S1E4:灵活但不算好用的Spring MVC

    阅读PDF版本 本文会以一些例子来展现Spring MVC的常见功能和一些扩展点,然后我们来讨论一下Spring MVC好用不好用. 使用SpringBoot快速开始 基于之前的parent模块,我们 ...

  4. 牛客练习赛B题 筱玛的排列(找递推规律)

    链接:https://ac.nowcoder.com/acm/contest/342/B来源:牛客网 筱玛的排列 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 524288K,其他语 ...

  5. python中map()函数用法

    map函数的原型是map(function, iterable, …),它的返回结果是一个列表. 参数function传的是一个函数名,可以是python内置的,也可以是自定义的. 参数iterabl ...

  6. Git使用过程中的问题

    Q-1:怎么切换到远程的分支 本地已经有一个代码库了(是从github上clone的),但是现在远程库中一个新的branch,怎么拉取远程分支,并在本地创建该分支(内容一样).how to do? # ...

  7. 阿里云ECS服务器云监控(cloudmonitor)Go语言版本插件安装卸载与维护

    云监控Go语言版本插件安装_主机监控_用户指南_云监控-阿里云https://help.aliyun.com/document_detail/97929.html 云监控cloudmonitor 1. ...

  8. Nginx会话保持之nginx-sticky-module模块

    Nginx会话保持之nginx-sticky-module模块 - 天行健,君子以自强不息:地势坤,君子以厚德载物. - CSDN博客https://blog.csdn.net/huangjinjin ...

  9. 搞站思路 <陆续完善中>

    只提供思路经验分享.不提供日站方法....一般站点那里最容易出现问题 入手思路: 主站一般都很安全.一般从二级域名下手 多看看那些大站新出来的测试分站点 猜路径别忘了google 考虑看站点下的rob ...

  10. # 【Python3练习题 008】判断101-200之间有多少个素数,并输出所有素数。

    lst = []for i in range(100): #建立 101-200 的列表 lst.append(101+i) for i in range(101, 201): #除数为 101-20 ...