zoukankan      html  css  js  c++  java
  • EntityFramework 学习 一 CRUD using Stored Procedure: 使用存储过程进行CRUD操作

    我们先创建如下3个存储过程

    1.Sp_InsertStudentInfo:

    CREATE PROCEDURE [dbo].[sp_InsertStudentInfo]
        -- Add the parameters for the stored procedure here
        @StandardId int = null,
        @StudentName varchar(50)
    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

    2.sp_UpdateStudent:

    CREATE PROCEDURE [dbo].[sp_UpdateStudent]
        -- Add the parameters for the stored procedure here
        @StudentId int,
        @StandardId int = null,
        @StudentName varchar(50)
    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

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

    将存储过程添加到EDM中

    实体浏览器将存储过程添加到存储模型中,但是不引进函数

    在EDM设计器中,右键Student实体,选择存储过程映射

     

     

     

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

    上面代码将执行如下存储过程

    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

     添加新实体,chontext上下文保存后,它将StudentId赋值,因为sp_InsertStudentInfo返回StudentId

  • 相关阅读:
    JavaScript 工作必知(九)function 说起 闭包问题
    AngularJs(七) 模块的创建
    javaScript 工作必知(八) 属性的特性 值、写、枚举、可配置
    javaScript 工作必知(七) 对象继承
    javaScript 工作必知(六) delete in instanceof
    数据可视化产品示例和相关文章
    echarts的世界地图json
    webstorm使用svn
    初识产品运维
    UglifyJS 压缩选项
  • 原文地址:https://www.cnblogs.com/lanpingwang/p/6622414.html
Copyright © 2011-2022 走看看