How to execute a Stored Procedure with Entity Framework Code First
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的更多相关文章
- Entity Framework Tutorial Basics(29):Stored Procedure in Entity Framework
Stored Procedure in Entity Framework: Entity Framework has the ability to automatically build native ...
- Entity Framework Code First执行SQL语句、视图及存储过程
1.Entity Framework Code First查询视图 Entity Framework Code First目前还没有特别针对View操作的方法,但对于可更新的视图,可以采用与Table ...
- Entity Framework Code First - Change Tracking
In this post we will be discussing about change tracking feature of Entity Framework Code First. Cha ...
- Entity Framework Code First学习系列目录
Entity Framework Code First学习系列说明:开发环境为Visual Studio 2010 + Entity Framework 5.0+MS SQL Server 2012, ...
- Entity Framework Code First数据库连接
1. 安装Entity Framework 使用NuGet安装Entity Framework程序包:工具->库程序包管理器->程序包管理器控制台,执行以下语句: PM> Insta ...
- Entity Framework Code First属性映射约定
Entity Framework Code First与数据表之间的映射方式有两种实现:Data Annotation和Fluent API.本文中采用创建Product类为例来说明tity Fram ...
- Entity Framework Code First关系映射约定
本篇随笔目录: 1.外键列名默认约定 2.一对多关系 3.一对一关系 4.多对多关系 5.一对多自反关系 6.多对多自反关系 在关系数据库中,不同表之间往往不是全部都单独存在,而是相互存在关联的.两个 ...
- Entity Framework Code First使用DbContext查询
DbContext.DbSet及DbQuery是Entity Framework Code First引入的3个新的类,其中DbContext用于保持数据库会话连接,实体变化跟踪及保存,DbSet用于 ...
- Entity Framework Code First添加修改及删除单独实体
对于一个单独实体的通常操作有3种:添加新的实体.修改实体以及删除实体. 1.添加新的实体 Entity Framework Code First添加新的实体通过调用DbSet.Add()方法来实现. ...
随机推荐
- java可重入锁reentrantlock
public class ReentrantDemo { //重入锁 保护临界区资源count,确保多线程对count操作的安全性 /*public static ReentrantLock rtlo ...
- 【LOJ 3049】「十二省联考 2019」字符串问题
这个D1T2绝对有毒... 首先我们构造一把反串的后缀自动机. 然后我们就需要找到每一个子串在SAM上的节点. 这个可以通过扫描线+树上倍增处理. 首先我们把所有的子串按照左端点排序, 然后从右往左扫 ...
- console 命令进行 JS 调试的灵活用法
1.console.log() 占位符 console.log 支持的占位符包括:字符(%s).整数(%d或%i).浮点数(%f)和对象(%o): console.log('字符串: %s, 整数: ...
- C#获取指定IP地址的数据库所有数据库实例名
/// <summary> /// 获取指定IP地址的数据库所有数据库实例名. /// </summary> /// <param name="ip" ...
- Dapper简易教程(翻译自Github上StackExchange/Dapper)
本文源自:https://github.com/cnxy/Dapper-zh-cn 本博客作者与Github上作者(cnxy)实为同一个作者.由于笔者翻译水平有限,文本中错误难免,欢迎指正! 本文翻译 ...
- C++与Java,C#的异同(一):值,地址,引用
Java,C#已经比较熟悉,最近在从0开始自学C++.学习过程中必然会与Java,C#进行对比,有吐槽,也有点赞. 先来讲讲最基本也是最重要的部分:参数传递的方式. 对于类型, Java分基本类型.复 ...
- Linux 命令(二)
man help:线上查询及帮助命令 命令 --help:简单帮助 help cd:查看一些Linux命令行的一些内置命令 文件和目操作命令(19个) ls cd cp find mkdi ...
- Leetcode 686 Repeated String Match
Given two strings A and B, find the minimum number of times A has to be repeated such that B is a su ...
- Sparse Principal Component Analysis
目录 背景: 部分符号 创新点 文章梗概 The LASSO AND THE ELASTIC NET 将PCA改造为回归问题 定理二 单个向量(无需进行SVD版本) 定理三 多个向量(无需进行SVD, ...
- Vue使用的一些实例
1.实现歌曲的点击切换. <!DOCTYPE html> <html lang="en"> <head> <meta charset=&q ...