【问题标题】:How Do I Pass Params To SP in EF6如何在 EF6 中将参数传递给 SP
【发布时间】:2016-09-23 16:01:19
【问题描述】:

我正在使用从教程文本中得到的模式。我正在使用 EF6,数据库优先。它是一种存储库模式。我不知道如何将参数传递给 SP。

有一个名为 EFRepository 的类,其中包含按 ID 返回完整表或记录的示例,如下所示:

public class EFRepository<T> : IRepository<T> where T : class
{
    public EFRepository(DbContext dbContext)
    {
        if (dbContext == null)
            throw new ArgumentNullException("dbContext");
        DbContext = dbContext;
        DbSet = DbContext.Set<T>();
    }

    protected DbContext DbContext { get; set; }
    protected DbSet<T> DbSet { get; set; }
    public virtual IQueryable<T> GetAll()
    {
        return DbSet;
    }

    public virtual T GetById(int id)
    {
        return DbSet.Find(id);
    }

接口类如下所示:

public interface IRepository<T> where T : class
{
    //To query using LINQ
    IQueryable<T> GetAll();
    //Return by ID
    T GetById(int id);

我尝试将其添加到 EF 存储库

   public virtual IQueryable<T> GetBySpParams(List<System.Data.SqlClient.SqlParameter> myParams)
    {
        return DbSet.Find(myParams);
    }

在界面中使用这个:

    IQueryable<T> GetBySpParams(List<System.Data.SqlClient.SqlParameter> myParams);

但这不起作用。我们将不胜感激。

【问题讨论】:

  • 那么究竟是什么不起作用?您没有展示如何使用 EF 调用 SP。 DBSet.Find 方法接受一个或多个对象并通过 id 搜索单个记录。它不调用任何 SP。
  • 从我的 api 中,我可以调用 GetAll 或 GetByID 并传递一个 int。我不能做(或不知道如何做)是调用存储过程并将其传递给参数。例如,我可以调用 var model = Uow.GetAll().OrderBy(m => m.Address).Select(m => new ContractedPropertyListModel
  • 如果你先做数据库,你应该有一个模型,一个 .edmx 文件?您可以从数据库中更新模型以包含 SP 并像函数一样调用 SP DbContext.SPName(p1,p2)
  • 模型有SP。模式实现存储库和接口的方式对我来说是个问题。

标签: c# .net asp.net-mvc entity-framework-6


【解决方案1】:

这是您可以使用参数调用存储过程的方式:

 /* Declare your parameters and their values */
 SqlParameter[] myParams = new SqlParameter[2];
 myParams[0] = new SqlParameter("startDate", startDate);
 myParams[1] = new SqlParameter("endDate", endDate);


 return dbContext.Database.SqlQuery<YourReturnDataType>("Exec YourStoreProcedureName @startDate, @endDate", myParams).ToList();

【讨论】:

  • return DbContext.SqlQuery("Exec YourStoreProcedureName @startDate, @endDate", myParams).ToList();错误 CS1061“DbContext”不包含“SqlQuery”的定义,并且找不到接受“DbContext”类型的第一个参数的扩展方法“SqlQuery”(您是否缺少 using 指令或程序集引用?)
  • 对不起。我更改了答案以解决该错误。基本上,DBContext 的 Database 属性有几个方法可以让你擦 SQL 命令。更好的解决方案是使用其中一种异步方法。
  • 这里是数据库类的链接:msdn.microsoft.com/en-us/library/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-03
  • 2021-12-27
  • 2021-09-18
  • 2018-08-14
  • 2011-01-27
相关资源
最近更新 更多