如何使用 EntityFramework 调用存储过程? [英] How to call Stored Procedures with EntityFramework?

查看:30
本文介绍了如何使用 EntityFramework 调用存储过程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从 MySQL 数据库生成了一个 EF4 模型,并且包含了 StoredProcedures 和表.

I have generated an EF4 Model from a MySQL database and I have included both StoredProcedures and Tables.

我知道如何对 EF 进行常规的插入/更新/获取/删除操作,但我找不到我的 StoredProcedures.

I know how to make regular instert/update/fetch/delete operations against the EF but I can't find my StoredProcedures.

这正是我所希望的:

using (Entities context = new Entities())
{
    context.MyStoreadProcedure(Parameters); 
}

编辑 1:

这是没有 EF 的样子:

This is how it looked without EF:

sqlStr = "CALL updateGame(?,?,?,?,?,?,?)";

commandObj = new OdbcCommand(sqlStr, mainConnection);
commandObj.Parameters.Add("@id,", OdbcType.Int).Value = inGame.id;
commandObj.Parameters.Add("@name", OdbcType.VarChar, 255).Value = inGame.name;
commandObj.Parameters.Add("@description", OdbcType.Text).Value = ""; //inGame.description;
commandObj.Parameters.Add("@yearPublished", OdbcType.DateTime).Value = inGame.yearPublished;
commandObj.Parameters.Add("@minPlayers", OdbcType.Int).Value = inGame.minPlayers;
commandObj.Parameters.Add("@maxPlayers", OdbcType.Int).Value = inGame.maxPlayers;
commandObj.Parameters.Add("@playingTime", OdbcType.VarChar, 127).Value = inGame.playingTime;    

return Convert.ToInt32(executeScaler(commandObj));

附注.如果需要,我可以更改 EF 版本

编辑 1:

CREATE DEFINER=`106228`@`%` PROCEDURE `updateGame`(
    inId INT,
    inName VARCHAR(255),
    inDescription TEXT,
    inYearPublished DATETIME,
    inMinPlayers INT,
    inMaxPlayers INT,
    inPlayingTime VARCHAR(127)
)

推荐答案

一种方法是使用 DbContext 之外的 Database 属性:

One way is to use the Database property off the DbContext:

SqlParameter param1 = new SqlParameter("@firstName", "Frank");
SqlParameter  param2 = new SqlParameter("@lastName", "Borland");
context.Database.ExecuteSqlCommand("sp_MyStoredProc @firstName, @lastName", 
                              param1, param2);

EF5 绝对支持这一点.

EF5 definitely supports that.

这篇关于如何使用 EntityFramework 调用存储过程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆