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 ...
随机推荐
- OpenCV-Python在图片上输出中文
OpenCV中在图片上输出中文一般需要借助FreeType库实现.FreeType库是一个完全免费(开源)的.高质量的且可移植的字体引擎,它提供统一的接口来访问多种字体格式文件.但使用FreeType ...
- LeetCode 336. Palindrome Pairs
原题链接在这里:https://leetcode.com/problems/palindrome-pairs/ 题目: Given a list of unique words, find all p ...
- 纯JS实现房贷利率报表对比
最近朋友买房,想计算下自己的房贷的还款情况,自己正好周末没事,从网上找来点代码修改,也算是对自己技术的巩固吧. 目前这个还只是个初级版本,暂时可以在PC上正常访问,将来会一步一步的把相继功能都加上的, ...
- 使用 MLCC 替代电解电容需要注意几点 (2018-07-23)
使用 MLCC 替代电解电容需要注意几点 容量,MLCC 在高压时容量会降到标称的 30~50% 以下 1. MLCC 的 ESR 很低,比较适合高频 DCDC 输出. MLCC 会有压电效应,可能会 ...
- linux user date
useradd username 添加用户 userdel username 删除用户 passwd username 设置用户密码 passwd 设置当前用户密码 passwd -d usernam ...
- 安装成功的nginx如何添加未编译模块?
在重启nginx后发生了错误,错误如下: nginx: [emerg] the "ssl" parameter requires ngx_http_ssl_module in /u ...
- canvas图形组合
代码: 1 /** 2 * Created by Administrator on 2016/1/27. 3 */ 4 function draw (id){ 5 var canvas = docum ...
- python 函数和方法的区别
一.函数和方法的区别 1.函数要手动传self,方法不用传 2.如果是一个函数,用类名去调用,如果是一个额方法,用对象去调用 举例说明: class Foo(object): def __init__ ...
- java.lang.ClassCastException: org.apache.catalina.connector.RequestFacade cannot be cast to org.springframework.web.multipart.MultipartHttpServletRequest
转自:https://blog.csdn.net/iteye_17476/article/details/82651580 java.lang.ClassCastException: org.apac ...
- myeclipse10启动service窗口报异常
1:找到与之对应的tomcat: 2:删掉“.metadata/.plugins/org.eclipse.core.runtime/.settings/ com.genuitec.eclipse.as ...