EF CodeFirst系列(6)---FluentApi配置存储过程

FluentApi配置存储过程

1.EF自动生成存储过程

  EF6的CodeFirst开发模式支持给实体的CUD操做配置存储过程,当咱们执行SaveChanges()方法时EF不在生成INSERT,UPDATE,DELETE命令,而是生成CUD操做的存储过程,咱们也能够给实体CUD操做指定自定义的存储过程。数据库

一个栗子:ide

咱们给学生实体的CUD操做设置存储过程,Student实体以下:ui

class Student
{
    public int StudentId { get; set; }
    public string StudentName { get; set; }
    public DateTime BirthDay { get; set; }
}

使用MapToStoredProcedures()方法能够让实体的CUD操做经过存储过程实现(这些存储过程由EF API自动生成),使用代码以下:spa

public class SchoolContext: DbContext 
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Student>()
                    //.MapToStoredProcedures();
    }

    public DbSet<Student> Students { get; set; }
}

运行一下代码:code

   class Program
    {
        static void Main(string[] args)
        {
            using (SchoolContext context=new SchoolContext())
            {
                //记录发往数据库的命令
                context.Database.Log = Console.Write;
                //添加
                Student stu1 = new Student() { StudentName = "Jack", Birthday = DateTime.Now.AddYears(-18) };
                context.Students.Add(stu1);
                context.SaveChanges();
                //修改
                stu1.StudentName = "Tom";
                context.SaveChanges();
                //删除
                context.Students.Remove(stu1);
                context.SaveChanges();
            }
        }
    }

运行结果以下:blog

若是取消上边代码中MapToStoredProcedures()方法的注释,那么运行后数据库添加了以下的存储过程:开发

程序运行结果以下:get

 2.给实体配置自定义存储过程

EF6中容许咱们使用自定义存储过程并将其映射到对应的实体。咱们也能够配置存储过程的参数。一个简单的栗子:string

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实体的CUD操做分别映射到sp_InsertStudentsp_UpdateStudentand sp_DeleteStudent三个存储过程,同时也配置了存储过程参数和实体属性间的映射。it

3.给全部实体配置存储过程

  咱们能够将全部实体的CUD操做都配置为存储过程形式的,使用以下代码就能够轻松实现:

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

注意:只用FluentApi能够配置存储过程的映射,数据注释属性不支持配置存储过程。咱们配置实体CUD的存储过程时要一块儿配置,只配置三个操做中的一个是不容许的。