Going through Tom Dykstra's Getting Started with Entity Framework 6 Code First using MVC 5 tutorial, part 9 covers how to set up EF6 to use stored procedures for CUD.
When the DepartmentSP
migration is added via the package manager console, the following CreateStoredProcedure() call is automatically generated to create the Department_Insert stored procedure:
CreateStoredProcedure(
"dbo.Department_Insert",
p => new
{
Name = p.String(maxLength: 50),
Budget = p.Decimal(precision: 19, scale: 4, storeType: "money"),
StartDate = p.DateTime(),
InstructorID = p.Int(),
},
body:
@"INSERT [dbo].[Department]([Name], [Budget], [StartDate], [InstructorID])
VALUES (@Name, @Budget, @StartDate, @InstructorID)
DECLARE @DepartmentID int
SELECT @DepartmentID = [DepartmentID]
FROM [dbo].[Department]
WHERE @@ROWCOUNT > 0 AND [DepartmentID] = scope_identity()
SELECT t0.[DepartmentID]
FROM [dbo].[Department] AS t0
WHERE @@ROWCOUNT > 0 AND t0.[DepartmentID] = @DepartmentID"
);
Why are there two SELECT
statements in the automatically generated stored procedure?
I tested the following simplification:
CreateStoredProcedure(
"dbo.Department_Insert",
p => new
{
Name = p.String(maxLength: 50),
Budget = p.Decimal(precision: 19, scale: 4, storeType: "money"),
StartDate = p.DateTime(),
InstructorID = p.Int(),
},
body:
@"INSERT [dbo].[Department]([Name], [Budget], [StartDate], [InstructorID])
VALUES (@Name, @Budget, @StartDate, @InstructorID)
SELECT t0.[DepartmentID]
FROM [dbo].[Department] AS t0
WHERE @@ROWCOUNT > 0 AND t0.[DepartmentID] = scope_identity()"
);
.. and this appears to work fine but I might be missing something.
I have read What's New in Entity Framework 6 (Plus How To Upgrade!) and the Code First Insert/Update/Delete Stored Procedure Mapping spec. Also, I looked through the EF6 git commit history and found commit 1911dc7, which is the first part of enabling stored procedure scaffolding in migrations.