Entity Framework Tutorial Basics(30):
CRUD using Stored Procedure:
In the previous chapter, we have seen how to get data using a stored procedure. In this chapter, we will use stored procedures for CUD (create, update, delete) operation using DbContext. That means context will execute stored procedures instead of DDL statements on context.SaveChanges().
We will use the following stored procedures:
- sp_InsertStudentInfo stored procedure to insert a new student into the database
- sp_UpdateStudent to update the student
- sp_DeleteStudent to delete the student in the database.
Sp_InsertStudentInfo:
CREATE PROCEDURE [dbo].[sp_InsertStudentInfo]
-- Add the parameters for the stored procedure here
@StandardId int = null,
@StudentName varchar
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON; INSERT INTO [SchoolDB].[dbo].[Student]([StudentName],[StandardId])
VALUES(@StudentName, @StandardId) SELECT SCOPE_IDENTITY() AS StudentId END
sp_UpdateStudent:
CREATE PROCEDURE [dbo].[sp_UpdateStudent]
-- Add the parameters for the stored procedure here
@StudentId int,
@StandardId int = null,
@StudentName varchar
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON; Update [SchoolDB].[dbo].[Student]
set StudentName = @StudentName,StandardId = @StandardId
where StudentID = @StudentId; END
sp_DeleteStudent
CREATE PROCEDURE [dbo].[sp_DeleteStudent]
-- Add the parameters for the stored procedure here
@StudentId int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON; DELETE FROM [dbo].[Student]
where StudentID = @StudentId END
First of all, add these stored procedures into EDM and make sure that the Import selected stored procedures and function into the entity model checkbox is unchecked as we will map these procedures with Student entity directly.
Now, Model Browser will add procedures into Storage model but not in Function Imports
In the EDM designer, right click on Student entity and select Stored Procedure Mapping to open Mapping details:
In the Mapping Details, you will see <Select Insert Function>, <Select Update Function>, and <Select Delete Function>. Select the appropriate stored procedure for each one, e.g. Select sp_InsertStudentInfo for Insert function, as shown below:
sp_InsertStudentInfo returns new auto generated StudentId. Map that with Student Entity’s StudentID as shown below:
Complete the mapping of Insert, Update and Delete procedures as shown below:
Now, we need to validate it before executing to ensure that there will not be a run time error. To accomplish this, right click on Student entity in the designer and click Validate and make sure that there are no warnings or errors:
Now you can add, update, and delete student as shown below:
using (var context = new SchoolDBEntities())
{
Student newStudent = new Student() { StudentName = "New Student using SP"}; context.Students.Add(newStudent);
//will execute sp_InsertStudentInfo
context.SaveChanges(); newStudent.StudentName = "Edited student using SP";
//will execute sp_UpdateStudent
context.SaveChanges(); context.Students.Remove(newStudent);
//will execute sp_DeleteStudentInfo
context.SaveChanges();
}
The code shown above will execute the following stored procedures on each SaveChanges():
exec [dbo].[sp_InsertStudentInfo] @StandardId=NULL,@StudentName='New Student using SP'
go exec [dbo].[sp_UpdateStudent] @StudentId=47,@StandardId=NULL,@StudentName='Edited student using SP'
go exec [dbo].[sp_DeleteStudent] @StudentId=47
go
Note: Once context calls SaveChanges after adding a new student, it will assign new StudentID to StudentID property of the Student entity because sp_InsertStudentInfo returns StudentId. This is necessary in order to use that entity object for further operation.
Download sample project for the demo.
Entity Framework Tutorial Basics(30):的更多相关文章
- Entity Framework Tutorial Basics(1):Introduction
以下系列文章为Entity Framework Turial Basics系列 http://www.entityframeworktutorial.net/EntityFramework5/enti ...
- Entity Framework Tutorial Basics(4):Setup Entity Framework Environment
Setup Entity Framework Environment: Entity Framework 5.0 API was distributed in two places, in NuGet ...
- Entity Framework Tutorial Basics(43):Download Sample Project
Download Sample Project: Download sample project for basic Entity Framework tutorials. Sample projec ...
- Entity Framework Tutorial Basics(42):Colored Entity
Colored Entity in Entity Framework 5.0 You can change the color of an entity in the designer so that ...
- Entity Framework Tutorial Basics(41):Multiple Diagrams
Multiple Diagrams in Entity Framework 5.0 Visual Studio 2012 provides a facility to split the design ...
- Entity Framework Tutorial Basics(37):Lazy Loading
Lazy Loading: One of the important functions of Entity Framework is lazy loading. Lazy loading means ...
- Entity Framework Tutorial Basics(36):Eager Loading
Eager Loading: Eager loading is the process whereby a query for one type of entity also loads relate ...
- Entity Framework Tutorial Basics(34):Table-Valued Function
Table-Valued Function in Entity Framework 5.0 Entity Framework 5.0 supports Table-valued functions o ...
- Entity Framework Tutorial Basics(33):Spatial Data type support in Entity Framework 5.0
Spatial Data type support in Entity Framework 5.0 MS SQL Server 2008 introduced two spatial data typ ...
随机推荐
- BEC listen and translation exercise 7
Maybe I ought to subscribe to the Engineering Quarterly.也许我应该订阅<工程学季刊>. The performance is sai ...
- dedecms列表页文章有图调用缩略图 无图留空或自定义图片的方法!
默认情况下,织梦的文章列表页会调用出当前栏目下的文章列表,并且调用出每个文章的缩略图:如果文章本身就有图,会调用出一张小图,如果没有,则会显示默认的织梦图片.这种处理方式有时候比较影响美观,其实可以修 ...
- shell变量扩展技巧
SHELL中有一些变量扩展的技巧,做下归纳总结 1.取字符串slice规则一:${变量名:位置起点}含义:由指定的位置起点开始,截取子字符串到字符串结束例如: var="/etc/passw ...
- BZOJ2784: [JLOI2012]时间流逝
BZOJ2784: [JLOI2012]时间流逝 https://lydsy.com/JudgeOnline/problem.php?id=2784 分析: 挺有意思的一道题. 注意到状态数是\(P( ...
- 学习动态性能表(10)--v$session_longops
学习动态性能表 第十篇--V$SESSION_LONGOPS 2007.6.7 本视图显示运行超过6秒的操作的状态.包括备份,恢复,统计信息收集,查询等等. 要监控查询执行进展状况,你必须使用cos ...
- 快速沃尔什变换(FWT)学习笔记
概述 FWT的大体思路就是把要求的 C(x)=A(x)×B(x) 即 \( c[i]=\sum\limits_{j?k=i} (a[j]*b[k]) \) 变换成这样的:\( c^{'}[i]=a^ ...
- 导入镜像后,容器内httpd起不来
导入镜像后发现bash进程为1 与之前apache启动的进程冲突了 解决办法:删除apache进程号,通过apachectl重启apache进程
- Azure disk iops的测试
在Public Cloud中,VM.Storage和Network是IaaS的三大基础.本文将介绍在Azure的VM上测试磁盘IOPS的工具和方法. 一.添加磁盘.初始化磁盘 1.添加磁盘 把相应的信 ...
- SQL简单嵌套查询与非嵌套查询的比较(MSSQL2005)
某天的工作是修复某个项目的bug,接着就发现,其sql极其混乱,有非常多的left join和in操作,还有嵌套查询(只有一个表的嵌套查询).不知道看到过哪里的资料说,嵌套查询速度慢,于是我把全部嵌套 ...
- 浅谈NB_LOT和LTE CAT M1
1.什么是NB-IoT? 窄带物联网(NB-IoT)也被称为LTE Cat NB1也是一种低功耗广域(LPWA,Low Power Wide Area)技术,它已经开发出来,可以使用现有的移动网络将各 ...