简体   繁体   English

在 Asp.Net MVC 5 中使用实体框架 6 代码优先方法调用存储过程

[英]Call stored procedures with Entity Framework 6 code first approach in Asp.Net MVC 5

We are using Ado.Net for working with the database from our C# code in ASP.NET MVC.我们正在使用 Ado.Net 来处理来自 ASP.NET MVC 中的 C# 代码的数据库。 I want to work with Entity Framework, so I need to use stored procedures with it, call stored procedures from EF.我想使用实体框架,所以我需要使用它的存储过程,从 EF 调用存储过程。

There are few examples how to use stored procedures with Entity Framework, but none specific for ASP.NET MVC and code-first (at least I couldn't find any).有几个示例如何在实体框架中使用存储过程,但没有一个特定于 ASP.NET MVC 和代码优先(至少我找不到任何示例)。

They are a good start but I need something more, better information and better examples!它们是一个好的开始,但我需要更多、更好的信息和更好的例子!

I have this stored procedure:我有这个存储过程:

Create Procedure spAddEmployee  
    @Name nvarchar(50),  
    @Gender nvarchar(20),  
    @Salary int,  
    @EmployeeId int Out  
as  
Begin  
    Insert into tblEmployees 
    values(@Name, @Gender, @Salary)  

    Select @EmployeeId = SCOPE_IDENTITY()  
 End

So @Name , @Salary , @Gender are input parameters, and @EmployeeId is an output parameter, it returns the ID of the newly added employee.所以@Name@Salary@Gender是输入参数,和@EmployeeId是一个输出参数,它返回ID新加入的雇员的。

Can someone tell me how to use Entity Framework (code-first) to call this stored procedure with the parameters?有人能告诉我如何使用实体框架(代码优先)来调用这个带有参数的存储过程吗?

You can call a stored procedure in your DbContext class as follows.您可以在DbContext类中调用存储过程,如下所示。

this.Database.SqlQuery<YourEntityType>("storedProcedureName",params);

Update:更新:

This is an Example how to call your SP in ActionResult:这是如何在 ActionResult 中调用 SP 的示例:

public ActionResult ExecuteProcedure()
{
   using(var  db = new CueEntities())
   {
     var parameter = 1;
     var query =  db.Database.SqlQuery<TestProcedure>("TestProcedure @parameter1", 
                    new  SqlParameter("@parameter1", parameter)).ToList();          
        return Json(query,JsonRequestBehavior.AllowGet);     
    }
}

Second Update:第二次更新:

For Multiple Params you can easily go like this:对于多个参数,您可以轻松地这样做:

var param1 = new SqlParameter(); 
param1.ParameterName = "@Value1"; 
param1.SqlDbType = SqlDbType.Int; 
param1.SqlValue = val1;

var param2 = new SqlParameter(); 
param2.ParameterName = "@Value2"; 
param2.SqlDbType = SqlDbType.NVarChar; 
param2.SqlValue = val2;

var result = db.tablename.SqlQuery("SP_Name @Value1,@Value2", param1, param2 ).ToList();

You should use CodeFirstStoredProcs library.您应该使用CodeFirstStoredProcs库。 It is best suited with Code first approach and it support all the features for stored procedure.它最适合代码优先方法,它支持存储过程的所有功能。 I am using it for many projects.我在许多项目中使用它。

Also you can use Code first user function library to call user defined functions also.您也可以使用 Code first 用户函数库来调用用户定义的函数。 I have created library for it.我已经为它创建了库。 CodeFirstFunctions 代码优先函数

Step 1:第1步:

Create your Stored Procedure script.创建您的存储过程脚本。

IF OBJECT_ID ( 'usp_GetUserByCompany', 'P' ) IS NOT NULL   
    DROP PROCEDURE usp_GetUserByCompany; 

GO
CREATE PROCEDURE usp_GetUserByCompany
    @__ProfileId [uniqueidentifier],
    @__CompanyId [uniqueidentifier],
    @__Email VARCHAR (MAX),
AS 
    SELECT *
    FROM [UserProfiles] AS [u]
    WHERE [u].[ProfileId] = @__ProfileId
        AND [u].[CompanyId] = @__CompanyId
        AND [u].[Email] = @__Email
GO

Step 2第2步

Create the Model for your Class为您的班级创建模型

public class UserProfile {
    public Guid Id { get;set; }
    public Guid CompanyId { get; set; }
    public Company Company { get;set; }
    public string Email { get;set; }
    ...
}

Step 3第 3 步

Go to your ApplicationDbContext class转到您的 ApplicationDbContext 类

public class ApplicationDbContext {

    ...
    
    public virtual DbQuery<UserProfile> UserProfiles { get; set; }
}

Step 4第四步

Create a migration for your Stored Procedure为您的存储过程创建迁移

dotnet ef migrations add Add_SP_GetUserProfileByCompany

Step 5第 5 步

Inside the generated migration class implement the Stored Procedure script on Step 1在生成的迁移类中实现步骤 1 中的存储过程脚本

public partial class Add_SP_GetUserProfileByCompany : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        var usp_GetUserByCompany = @"
            IF OBJECT_ID ( 'usp_GetUserByCompany', 'P' ) IS NOT NULL   
                DROP PROCEDURE usp_GetUserByCompany; 
            
            GO
            CREATE PROCEDURE usp_GetUserByCompany
                @__ProfileId [uniqueidentifier],
                @__CompanyId [uniqueidentifier],
                @__Email VARCHAR (MAX),
            AS 
                SELECT *
                FROM [UserProfiles] AS [u]
                WHERE [u].[ProfileId] = @__ProfileId
                    AND [u].[CompanyId] = @__CompanyId
                    AND [u].[Email] = @__Email
            GO
        ";

        migrationBuilder.Sql(usp_GetUserByCompany);
    }
    ...
}

Step 6第 6 步

In your code somewhere on the system or services etc.,在系统或服务等的某个地方的代码中,

public List<UserProfile> GetUserProfileByCompanySP(Guid ProfileId, Guid CompanyId, string Email)
{
    var dbContext = new ApplicationDbContext;

    var parameters = new object[]
    {
        new SqlParameter() {ParameterName = "@__ProfileId", Direction = ParameterDirection.Input, SqlDbType = SqlDbType.UniqueIdentifier, Value = ProfileId},
        new SqlParameter() {ParameterName = "@__CompanyId", Direction = ParameterDirection.Input, SqlDbType = SqlDbType.UniqueIdentifier, Value = CompanyId},
        new SqlParameter() {ParameterName = "@__Email", Direction = ParameterDirection.Input, SqlDbType = SqlDbType.VarChar, Size = 64, Value = Email},
    };

    var output = dbContext.UserProfiles.FromSql("usp_GetUserByCompany @__ProfileId, @__CompanyId, @__Email", parameters).ToList();
    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用实体框架的代码优先方法在ASP.NET MVC应用程序中缺少外键关系 - Foreign key relationship missing in ASP.NET MVC app using code-first approach with Entity Framework 如何使用实体框架在ASP.NET MVC中调用存储过程 - How to call stored procedure in ASP.NET MVC with Entity Framework 具有实体框架代码优先导航属性的ASP.Net MVC - ASP.Net MVC with Entity Framework Code First Navigation Property 代码优先实体框架Asp.net MVC - Code First Entity Framework Asp.net MVC 在ASP.NET Web表单中使用Entity Framework(代码优先方法)在Repeater控件中显示详细信息 - Show details in Repeater control using Entity Framework (code first approach) in asp.net webforms ASP.net MVC 4 EF5中的代码优先方法混乱 - Code First Approach Confusion in ASP.net MVC 4 EF5 ASP.NET 核心实体框架调用存储过程 - ASP.NET Core Entity Framework call stored procedure 在Code First Entity Framework中指定除dbo之外的SQL用户名(C#ASP.NET MVC 3) - Specify an SQL username other than dbo in Code First Entity Framework ( C# ASP.NET MVC 3 ) 使用实体框架代码优先的ASP.NET MVC 3 Web应用程序上的列名ProveedoresID和UsuarioID无效 - Invalid column name ProveedoresID and UsuarioID on ASP.NET MVC 3 web app using Entity Framework Code First 首先在ASP.net MVC实体框架代码中创建外键关系 - Create Foreign Key Relationship in ASP.net MVC Entity Framework Code First
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM