在实体框架中使用存储过程 [英] using stored procedure in entity framework
问题描述
我正在使用asp.net mvc 5 和C# 与实体框架...我有模型和域类的功能...现在我需要使用存储过程...我在运动中挣扎.
I am using asp.net mvc 5 and C# with Entity Framework... I have model and domain classes for function... now I need to use stored procedure.... which I am struggling at the movement.
我首先遵循现有数据库的代码,并且在那里编写了存储过程.我的问题是如何在我的 Web 应用程序中调用该存储过程.
I am following code first existing database and I have stored procedure written there. My question is how I can call that stored procedure in my web application.
存储过程:
ALTER PROCEDURE [dbo].[GetFunctionByID](
@FunctionId INT
)
AS
BEGIN
SELECT *
FROM Functions As Fun
WHERE Function_ID = @FunctionId
END
域类:
public class Functions
{
public Functions()
{
}
public int Function_ID { get; set; }
public string Title { get; set; }
public int Hierarchy_level { get; set; }
}
功能模型:
[Table("Functions")]
public class App_Functions
{
public App_Functions()
{
}
[Key]
public int Function_ID { get; set; }
[StringLength(50)]
[Required]
public string Title { get; set; }
public int Hierarchy_level { get; set; }
//public virtual ICollection<App_Controllers> App_Controllers { get; set; }*/
}
基本上下文:
public class BaseContext<TContext> : DbContext where TContext : DbContext
{
static BaseContext()
{
Database.SetInitializer<TContext>(null);
}
protected BaseContext()
: base("name = ApplicationDbConnection")
{ }
}
函数上下文:
public class FunctionsContext : BaseContext<FunctionsContext>
{
public DbSet<App_Functions> Functions { get; set; }
}
推荐答案
您需要创建一个包含所有存储过程属性的模型类,如下所示.也因为实体框架模型类需要主键,你可以使用 Guid 创建一个假键.
You need to create a model class that contains all stored procedure properties like below. Also because Entity Framework model class needs primary key, you can create a fake key by using Guid.
public class GetFunctionByID
{
[Key]
public Guid? GetFunctionByID { get; set; }
// All the other properties.
}
然后在您的 DbContext
中注册 GetFunctionByID
模型类.
then register the GetFunctionByID
model class in your DbContext
.
public class FunctionsContext : BaseContext<FunctionsContext>
{
public DbSet<App_Functions> Functions { get; set; }
public DbSet<GetFunctionByID> GetFunctionByIds {get;set;}
}
当您调用存储过程时,请参见以下内容:
When you call your stored procedure, just see below:
var functionId = yourIdParameter;
var result = db.Database.SqlQuery<GetFunctionByID>("GetFunctionByID @FunctionId", new SqlParameter("@FunctionId", functionId)).ToList());
这篇关于在实体框架中使用存储过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!