【问题标题】:How to import existing stored procedure in Entity Framework code-first from entity data wizard?如何从实体数据向导导入实体框架代码中的现有存储过程?
【发布时间】:2018-10-02 21:16:20
【问题描述】:

今天我首先使用现有的数据库方法来模拟代码。但是在 VS 2017 中的实体数据模型向导 -> 将选定的存储过程导入实体模型复选框中的功能被禁用。请看附件截图:

Entity Data Model Wizard.

那么如何启用该选项?

【问题讨论】:

    标签: c# visual-studio-2017 entity-framework-6


    【解决方案1】:

    您不需要导入程序。

    代码示例中显示了现有存储过程(InsertStudent、UpdateStudent)的使用。只需要覆盖OnModelCreating 方法并用实体映射存储过程。

    请参阅此页面http://www.entityframeworktutorial.net/EntityFramework6/code-first-insert-update-delete-stored-procedure-mapping.aspx了解详细信息。

    public class SchoolContext: DbContext 
    {
       protected override void OnModelCreating(DbModelBuilder modelBuilder)
       {
    
         modelBuilder.Entity<Student>()
            .MapToStoredProcedures(p => p.Insert(sp => sp.HasName("InsertStudent").Parameter(pm => pm.StudentName, "name").Result(rs => rs.StudentId, "Id"))
                .Update(sp => sp.HasName("UpdateStudent").Parameter(pm => pm.StudentName, "name"))
                .Delete(sp => sp.HasName("DeleteStudent").Parameter(pm => pm.StudentId, "Id"))
            );
       }
    }
    

    【讨论】:

    • 旁注:您应该为您的存储过程使用sp_ 前缀。微软有reserved that prefix for its own use (see Naming Stored Procedures),你确实会在未来某个时候冒着名称冲突的风险。 It's also bad for your stored procedure performance。最好只是简单地避免 sp_ 并使用其他东西作为前缀 - 或者根本不使用前缀!
    • @marc_s,是的,我明白了,我不需要导入存储过程。但是我的数据库中已经存在的存储过程呢?这是否意味着,我不再使用它们了?
    • 嗨@narendras14,你读过答案中给出的代码吗?它正在使用现有的存储过程(InsertStudent、UpdateStudent)。您需要覆盖 OnModelCreating 方法并使用实体映射存储过程。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-28
    • 1970-01-01
    • 2017-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多