Entity Framework 6.0 Tutorials(9):Stored Procedure Mapping

本文介绍如何使用Entity Framework 6 Code-First创建并映射存储过程进行增删改操作。通过Fluent API可以为实体类型自动创建插入、更新和删除的存储过程,并提供了更改存储过程及参数名称的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

转载于:https://www.cnblogs.com/purplefox2008/p/5649576.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值