Entity Framework 6.0 Tutorials(9):Stored Procedure Mapping
2016-07-07 11:52
357 查看
Code First - Insert, Update, Delete Stored Procedure Mapping:
Entity Framework 6 Code-First provides the ability to create and use a stored procedure for add, update, and delete operations. This was not possible in the previous versions of Entity Framework.Student Entity:
class Student { public Student() { } public int Student_ID { get; set; } public string StudentName { get; set; } }
The following example automatically creates a stored procedure for Student entity using Fluent API.
protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Student>() .MapToStoredProcedures(); }
The code shown above will create three procedures Student_Insert, Student_Update and Student_Delete. Student_Insert and Student_Update stored procedures have a parameter name which corresponds to the property names. Student_Delete will have a primary key property StudentID parameter.
You can also change the stored procedure and parameter names, as shown below:
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.Student_ID, "Student_ID")) .Update(sp => sp.HasName("sp_UpdateStudent").Parameter(pm => pm.StudentName, "name")) .Delete(sp => sp.HasName("sp_DeleteStudent").Parameter(pm => pm.Student_ID, "Id")) ); }
If you want all your entities to use stored procedures, then do the following:
protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Types().Configure(t => t.MapToStoredProcedures()); }
Limitations:
Only Fluent API can be used to map stored procedures. You cannot use Data Annotation attributes in EF 6 for stored procedure mapping.You cannot use a mixture of stored procedure and query to add, update and delete operation on the same entity. You can either use stored procedure or SQL query for all add, update and delete operations with the entity.
Download sample project for demo.
Visit codeplex documentation for more information.
相关文章推荐
- 为webview添加头尾,可适用于textview
- Shadow Map 原理和改进
- android 6.0 以后 WebView改动
- 用tophat 将clear reads mapping 到植物基因组上
- 自定义只有上下边界的边框背景
- objective-C 编程全解-第15章 消息发送模式 下 NSUndoManager 撤销管理器
- 根据日期计算是星期几
- Android 自定义View (一)
- IOS Top100的第三方库整理
- objective-C 编程全解-第15章 消息发送模式 中
- iOS 无线打印功能(AirPrint)
- Swift - 自定义tabbar的封装
- Objective-C 编程全解-第15章 消息发送模式 上
- 在Android String文件中使用CDATA
- 一个App与另一个App之间的交互,添加了自己的一些理解
- 一个App与另一个App之间的交互,添加了自己的一些理解
- 微信APP支付Java代码
- Android 测试环境噪音分贝
- Android Volley框架的几种post提交请求方式
- AndroidStudio的PullToRefreshListView简单使用