【译】第44节---EF6-存储过程映射

原文:http://www.entityframeworktutorial.net/entityframework6/code-first-insert-update-delete-stored-procedure-mapping.aspx

EF6 Code-First提供了创建和使用存储过程以添加,更新和删除操作的功能。 这在以前的Entity Framework版本中是没有的。

Student实体:

class Student
{
    public Student()
    {
    }

    public int Student_ID { get; set; }
    public string StudentName { get; set; }
}

以下示例使用Fluent API自动为Student实体创建一个存储过程:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Student>()
        .MapToStoredProcedures();
}

上面显示的代码将创建三个存储过程Student_Insert,Student_Update和Student_Delete。

Student_Insert和Student_Update存储过程具有与属性名称对应的参数名称, Student_Delete将具有主键属性StudentID参数。

还可以更改存储过程和参数名称,如下所示:

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"))
        );
}

如果希望所有实体使用存储过程,请执行以下操作:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Types().Configure(t => t.MapToStoredProcedures());
}

限制:
只有Fluent API可用于映射存储过程,不能在EF 6中使用数据注解属性进行存储过程映射。
不能使用存储过程和查询的混合来在同一个实体上添加,更新和删除操作。

原文地址:https://www.cnblogs.com/talentzemin/p/7411200.html