EF 6 Code-First系列文章目錄:數據庫
當SaveChanges方法被調用的時候,EF 6 能夠用來建立並使用增刪改存儲過程。app
咱們來爲下面的Student實體,建立增刪改存儲過程。ide
class Student { public int StudentId { get; set; } public string StudentName { get; set; } public DateTime DoB { get; set; } }
使用MapToStoredProcedures()方法,爲實體配置默認的存儲過程。測試
public class SchoolContext: DbContext { protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Student>() .MapToStoredProcedures(); } public DbSet<Student> Students { get; set; } }
EF API將會爲Student實體建立Student_Insert
, Student_Update
和Student_Delete存儲過程。
ui
Student_Insert和Student_Update存儲過程包含Student實體的全部屬性的參數,Student_Delete存儲過程僅僅包含Student的主鍵屬性StudentID一個參數:spa
CREATE PROCEDURE [dbo].[Student_Insert] @StudentName [nvarchar](max), @DoB [datetime] AS BEGIN INSERT [dbo].[Students]([StudentName], [DoB]) VALUES (@StudentName, @DoB) DECLARE @StudentId int SELECT @StudentId = [StudentId] FROM [dbo].[Students] WHERE @@ROWCOUNT > 0 AND [StudentId] = scope_identity() SELECT t0.[StudentId] FROM [dbo].[Students] AS t0 WHERE @@ROWCOUNT > 0 AND t0.[StudentId] = @StudentId END CREATE PROCEDURE [dbo].[Student_Update] @StudentId [int], @StudentName [nvarchar](max), @DoB [datetime] AS BEGIN UPDATE [dbo].[Students] SET [StudentName] = @StudentName, [DoB] = @DoB WHERE ([StudentId] = @StudentId) END CREATE PROCEDURE [dbo].[Student_Delete] @StudentId [int] AS BEGIN DELETE [dbo].[Students] WHERE ([StudentId] = @StudentId) END
爲實體映射自定義的存儲過程.net
EF6容許你使用本身的存儲過程,你能夠像下面這樣進行配置,下面的代碼爲Student實體,映射了一個自定義的存儲過程。翻譯
protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Student>() .MapToStoredProcedures(p => p.Insert(sp => sp.HasName("sp_InsertStudent").Parameter(pm => pm.StudentName, "name").Result(rs => rs.StudentId, "Id")) .Update(sp => sp.HasName("sp_UpdateStudent").Parameter(pm => pm.StudentName, "name")) .Delete(sp => sp.HasName("sp_DeleteStudent").Parameter(pm => pm.StudentId, "Id")) ); }
在上面的例子中,Student實體映射了三個存儲過程,sp_InsertStudent、sp_UpdateStudent、以及sp_DeleteStudent.固然一樣對存儲過程的參數進行了配置。code
爲全部實體配置存儲過程
你能夠使用下面的代碼,爲全部實體配置存儲過程。
protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Types().Configure(t => t.MapToStoredProcedures()); }
侷限性