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

  • 相关阅读:
    day23 笔记
    iframe子页面与父页面通信
    js格式化时间
    自定义滚动条样式
    表格隔行换色
    css除第一个子元素的其他子元素的4种方法,超实用!
    子div在父div里居中
    红橙黄绿蓝靛紫-RGB-十六进制
    阿里巴巴矢量图标库 字体图标的下载与使用
    calc属性不生效
  • 原文地址:https://www.cnblogs.com/lanpingwang/p/6622414.html
Copyright © 2011-2022 走看看