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);

How to execute a Stored Procedure with Entity Framework Code First的更多相关文章

  1. Entity Framework Tutorial Basics(29):Stored Procedure in Entity Framework

    Stored Procedure in Entity Framework: Entity Framework has the ability to automatically build native ...

  2. Entity Framework Code First执行SQL语句、视图及存储过程

    1.Entity Framework Code First查询视图 Entity Framework Code First目前还没有特别针对View操作的方法,但对于可更新的视图,可以采用与Table ...

  3. Entity Framework Code First - Change Tracking

    In this post we will be discussing about change tracking feature of Entity Framework Code First. Cha ...

  4. Entity Framework Code First学习系列目录

    Entity Framework Code First学习系列说明:开发环境为Visual Studio 2010 + Entity Framework 5.0+MS SQL Server 2012, ...

  5. Entity Framework Code First数据库连接

    1. 安装Entity Framework 使用NuGet安装Entity Framework程序包:工具->库程序包管理器->程序包管理器控制台,执行以下语句: PM> Insta ...

  6. Entity Framework Code First属性映射约定

    Entity Framework Code First与数据表之间的映射方式有两种实现:Data Annotation和Fluent API.本文中采用创建Product类为例来说明tity Fram ...

  7. Entity Framework Code First关系映射约定

    本篇随笔目录: 1.外键列名默认约定 2.一对多关系 3.一对一关系 4.多对多关系 5.一对多自反关系 6.多对多自反关系 在关系数据库中,不同表之间往往不是全部都单独存在,而是相互存在关联的.两个 ...

  8. Entity Framework Code First使用DbContext查询

    DbContext.DbSet及DbQuery是Entity Framework Code First引入的3个新的类,其中DbContext用于保持数据库会话连接,实体变化跟踪及保存,DbSet用于 ...

  9. Entity Framework Code First添加修改及删除单独实体

    对于一个单独实体的通常操作有3种:添加新的实体.修改实体以及删除实体. 1.添加新的实体 Entity Framework Code First添加新的实体通过调用DbSet.Add()方法来实现. ...

随机推荐

  1. face detection[PyramidBox]

    本文来自<PyramidBox: A Context-assisted Single Shot Face Detector>,是来自百度的作品,时间线为2018年8月. 0 引言 最近基于 ...

  2. linux配置PS1

    自己常用的格式: vi ~/.bashrc export PS1="\[\e[31;1m\]\u@\[\e[34;1m\]\h \[\e[36;1m\]\W $\[\e[37;1m\] &q ...

  3. Burp Suite学习之Intruder的4种攻击模式

    burp suit的intruder攻击共有四种模式,如图所示,下面分别讲讲这四种模式的使用方法和场景. 一 .Sniper模式 Sniper模式使用一组payload集合,它一次只使用一个paylo ...

  4. 高并发下的Id生成器

    考虑到sql server以及c#,最多只能用decimal类型,也就是29位的数字,做了下面这个数字型id生成器: class Program { static void Main(string[] ...

  5. 从.Net框架Bug的提交到修复代码成功合并到.NET CoreFX主线

    从发现.NET Framework中SmtpClient的Bug并拿出解决方案,然后给微软开发者社区提交Bug开始,总共耗时一个多月,对Bug修复的代码最终被采纳,现已合并到.NET Core Lib ...

  6. (通用版)salesforce中soql及sosl的伪‘Like’模糊检索

    salesforce里有soql.sosl两种查询语法,soql针对模糊搜索也有‘like’关键字,然而只能针对其自带字段如:Name.Id:对于自定义添加的字段如:Message__c.Note__ ...

  7. SQL Server(2000,2005,2008):恢复/回滚时间比预期长(译)

    我已经讨论了各种确定恢复状态的方法,但是本周我参与了一个围绕回滚的有趣讨论.交易已经运行了14个小时,然后发出了KILL SPID.SPID进入回滚,并发生2天和4小时. 自然的问题是为什么不14小时 ...

  8. Python_每日习题-0008-九九乘法表

    题目: 输出9*9乘法口诀表. 程序分析:分行与分列的考虑,共9行9列,i控制行,j控制列. for i in range(1, 10): for j in range(1, i+1): print( ...

  9. Sparse Principal Component Analysis via Rotation and Truncation

    目录 对以往一些SPCA算法复杂度的总结 Notation 论文概述 原始问题 问题的变种 算法 固定\(X\),计算\(R\) 固定\(R\),求解\(X\) (\(Z =VR^{\mathrm{T ...

  10. Truncated Power Method for Sparse Eigenvalue Problems

    目录 算法 k的选择 \(x\)的初始化 代码 抱歉,真的没怎么看懂,当然,估计和我现在没法静下心来好好看也有关系. 算法 想法非常非常简单吧,就是在原来幂法的基础上,每次迭代的时候再加个截断.当然, ...