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

 

posted @ 2017-03-26 12:39  蓝平凡  阅读(301)  评论(0编辑  收藏  举报