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:

  1. sp_InsertStudentInfo stored procedure to insert a new student into the database
  2. sp_UpdateStudent to update the student
  3. 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):的更多相关文章

  1. Entity Framework Tutorial Basics(1):Introduction

    以下系列文章为Entity Framework Turial Basics系列 http://www.entityframeworktutorial.net/EntityFramework5/enti ...

  2. 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 ...

  3. Entity Framework Tutorial Basics(43):Download Sample Project

    Download Sample Project: Download sample project for basic Entity Framework tutorials. Sample projec ...

  4. 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 ...

  5. Entity Framework Tutorial Basics(41):Multiple Diagrams

    Multiple Diagrams in Entity Framework 5.0 Visual Studio 2012 provides a facility to split the design ...

  6. Entity Framework Tutorial Basics(37):Lazy Loading

    Lazy Loading: One of the important functions of Entity Framework is lazy loading. Lazy loading means ...

  7. 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 ...

  8. 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 ...

  9. 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 ...

随机推荐

  1. ios开发小技巧(转)

    1.通过下面方式可以获取图片的像素颜色点:- (void*)getImageData:(UIImage*)image{    void* imageData;    if (imageData == ...

  2. MySql数据库约束

    <MySQL技术内幕:InnoDB存储引擎>本书从源代码的角度深度解析了InnoDB的体系结构.实现原理.工作机制,并给出了大量实践,本着将书读薄的思想,循序渐进的记录对本书学习的读书笔记 ...

  3. 如果两个人,两台电脑同时登录同一个帐号,同时对同一个账单提交,账单同时被服务器处理,那服务器应该先处理谁的,或者怎么规避这个问题。 非单点登录,重定向,stoken拦截器的问题

    方法一:给用户设置个状态 服务器端坐标记,比如数据库中增加一列,标识是否登陆,登录时先判断这个就行了,不过要考虑非正常退出的情况 http 方法二:在用户表里面 多加一个状态字段,登录成功 改变状态  ...

  4. Net Core 中使用 Consul 来存储配置

    Net Core 中使用 Consul 来存储配置 https://www.cnblogs.com/Rwing/p/consul-configuration-aspnet-core.html 原文: ...

  5. vbox sethduuid

    laozha@abc$ /usr/bin/vboxmanage internalcommands sethduuid /ud1/VBOX/centos7/CentOS7.vdi UUID change ...

  6. DWZ富客户端HTML框架

    一.了解 概述:是中国人自己开发的基于jQuery实现的Ajax RIA开源框架. 目的:简单实用.扩展方便(在原有架构基础上扩展方便).快速开发.RIA思路.轻量级 使用:用html扩展的方式来代替 ...

  7. LeetCode第一题:Two Sum

    Given an array of integers, return indices of the two numbers such that they add up to a specific ta ...

  8. Azure上采用Powershell从已有的VHD创建VM

    刚刚的一篇Blog采用Json Template的方式从已有的VHD创建了一台新的VM.由于Json Template封装的比较好,可以改的内容不多. 下面将介绍通过用Powershell来从已有的V ...

  9. 如何隐藏掉Nginx的版本号

    最近新学习了一个命令curl,里面有一个参数-I可以查看到网站使用的是哪种服务器,比如: zhangxiaoliudeMacBook-Pro-2:~ zhangxiaoliu$ curl -I htt ...

  10. Linux驱动 - SPI驱动 之四 SPI数据传输的队列化

    我们知道,SPI数据传输可以有两种方式:同步方式和异步方式.所谓同步方式是指数据传输的发起者必须等待本次传输的结束,期间不能做其它事情,用代码来解释就是,调用传输的函数后,直到数据传输完成,函数才会返 ...