加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 在实体框架中使用存储过程

发布时间:2020-12-15 19:08:20 所属栏目:asp.Net 来源:网络整理
导读:我使用asp.net mvc 5和C#与Entity框架…我有函数的模型和域类…现在我需要使用存储过程….这是我正在努力的运动。 我下面的代码第一个现有的数据库,我有存储过程写在那里。我的问题是如何可以在我的Web应用程序中调用该存储过程。 存储过程: ALTER PROCEDU
我使用asp.net mvc 5和C#与Entity框架…我有函数的模型和域类…现在我需要使用存储过程….这是我正在努力的运动。

我下面的代码第一个现有的数据库,我有存储过程写在那里。我的问题是如何可以在我的Web应用程序中调用该存储过程。

存储过程:

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; }*/
}

BaseContext:

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; }
}

解决方法

您需要创建一个包含所有存储过程属性的模型类,如下所示。
另外因为Entity Framework模型类需要主键,所以可以使用Guid创建一个假键。
public class GetFunctionByID
{
    [Key]
    public Guid? GetFunctionByID { get; set; }

    // All the other properties.
}

然后在您的DbContext中注册GetFunctionByID模型类。

public class FunctionsContext : BaseContext<FunctionsContext>
{
    public DbSet<App_Functions> Functions { get; set; }
    public DbSet<GetFunctionByID> GetFunctionByIds {get;set;}
}

当你调用存储过程时,只需看下面:

var functionId = yourIdParameter;
var result =  db.Database.SqlQuery<GetFunctionByID>("GetFunctionByID @FunctionId",new SqlParameter("@FunctionId",functionId)).ToList());

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读