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. ODOO(ERP源码安装)

    cat /etc/centos-release CentOS Linux release 7.4.1708 (Core) uname -r 3.10.0-693.el7.x86_64 IP:192.1 ...

  2. 利用Oracle分析函数row_number和sys_connect_by_path实现多行数据合并为一行

    emo场景,以oracle自带库中的表emp为例: select ename,deptno from emp order by deptno; ENAME DEPTNO CLARK 10 KING 1 ...

  3. 还是要习惯在linux环境下作Java开发

    要FQ 怎么在ubuntu上安装jdk 网址: https://www.youtube.com/watch?v=NZB3Iy7Lve4 需要网站:http://p.web.umkc.edu/pv6xc ...

  4. Chrome 谷歌浏览器清除HTTPS证书缓存

    在地址栏输入 chrome://net-internals/#hsts 找到下图中的输入框,输入对于的域名执行删除就行了

  5. C#.NET 大型通用信息化系统集成快速开发平台 4.6 版本 - SSO单点登录接口

    当开发的系统多了.用户多了.合作伙伴多了.对接厂商多了.开发人员多了.部署的服务器也多了,各种安全问题就暴露出来了. 如何安全的把这些系统集成在一起?实现集群的单点登录.严格统一的用户安全体系管理? ...

  6. Python—re模块

    re模块 正则表达式就是字符串的匹配规则,在多数编程语言里都有相应的支持,python里对应的模块是re 常用的表达式规则 '.' 默认匹配除\n之外的任意一个字符,若指定flag DOTALL,则匹 ...

  7. iOS NSDictionary JSON 相互转换

    /*! * @brief 把格式化的JSON格式的字符串转换成字典 * @param jsonString JSON格式的字符串 * @return 返回字典 */ + (NSDictionary * ...

  8. Python2和Python3中urllib库中urlencode的使用注意事项

    前言 在Python中,我们通常使用urllib中的urlencode方法将字典编码,用于提交数据给url等操作,但是在Python2和Python3中urllib模块中所提供的urlencode的包 ...

  9. 学习WebSocket

    初识WebSocket: index.html <!DOCTYPE html> <html> <head> <meta charset="UTF-8 ...

  10. semantic-ui 标题

    在semantic-ui中定义了5中标题样式,注意HTML中有h1-h6,而semantic-ui中只有h1-h5. 不过需要注意的是,semantic-ui的标题仍旧使用h1-h5来表示,但是在cl ...