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

  • 相关阅读:
    (十六)分页
    (十五)条件查询
    (十四)hibernate逆向工程
    (十三)信息发布管理
    (十二)系统权限
    (十一)角色管理
    (十)系统异常处理
    (九)表单校验
    POI操作Excel
    (八)头像上传
  • 原文地址:https://www.cnblogs.com/lanpingwang/p/6622414.html
Copyright © 2011-2022 走看看