zoukankan      html  css  js  c++  java
  • Entity Framework 6.0 Tutorials(9):Stored Procedure Mapping

    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.

  • 相关阅读:
    基于 HTML5 + WebGL 实现的垃圾分类系统
    B/S 端基于 HTML5 + WebGL 的 VR 3D 机房数据中心可视化
    基于 Web 端 3D 地铁站可视化系统
    HTML5 + WebGL 实现的垃圾分类系统
    基于HTML5 WebGL的工业化3D电子围栏
    iOS 不支持 PWA,那又怎么样?
    PWA 入门: 写个非常简单的 PWA 页面
    iOS UTI
    canOpenURL: failed for URL: "weixin://app/wx 问题解决方式
    iOS扩大UIButton按钮的可点击区域
  • 原文地址:https://www.cnblogs.com/purplefox2008/p/5649576.html
Copyright © 2011-2022 走看看