【问题标题】:CodeFirst calling stored procedureCodeFirst 调用存储过程
【发布时间】:2014-10-01 21:04:49
【问题描述】:

我正在为我的程序使用 CodeFirst 和存储库模式。我用作上下文的数据库有一个我在 SQL Server Management Studio 中创建和测试的存储过程,名为 dbo.sp_InsertTrackingInfo。

在我的基础存储库类中,我有

public IEnumerable<T> ExecWithStoreProcedure(string query, int id)
{
    return _context.Database.SqlQuery<T>("sp_InsertTrackingInfo @estimate", new SqlParameter("estimate", id));
}

在管理工作室中使用此查询有效,其中估计定义为整数

EXEC sp_InsertTrackingInfo @estimate = '14'

除此之外的所有操作都可以正常工作,因此我知道我指向了正确的位置,我检查了 SQL Server Profiler,并且在调用此函数的任何时候都没有调用此过程。

有人有这方面的经验吗?

谢谢, 麦基

编辑:

在其中一个存储库中

using (var uow = UnitOfWorkManager.Begin())
{
    uow.EstimateTrackingRepository.Insert(t);
    uow.EstimateTrackingRepository.ExecWithStoreProcedure("exec sp_InsertTrackingInfo @estimate", t.EstimateId);
    uow.Commit();
}

【问题讨论】:

  • 哪个代码调用了ExecWithStoreProcedure?
  • 我将其添加到编辑中
  • 我认为您需要在SqlQuery 之后或在调用ExecWithStoreProcedure 之后使用ToArray() 之类的内容执行查询,该过程是否在插入语句之后执行选择查询?如果它只是一个插入语句,可能你可以使用ExecuteSqlCommand。
  • 旁注:您应该不为您的存储过程使用sp_ 前缀。微软有reserved that prefix for its own use (see Naming Stored Procedures),你确实会在未来某个时候冒着名称冲突的风险。 It's also bad for your stored procedure performance。最好只是简单地避免 sp_ 并使用其他东西作为前缀 - 或者根本不使用前缀!
  • 另外:它是一个 stored 过程 - 就像在 SQL Server 中的 stored 中一样 - 它与 store 因此它不是 存储过程 ....

标签: c# sql sql-server stored-procedures ef-code-first


【解决方案1】:

如果过程只是执行插入语句,您可以使用ExecuteSqlCommand。

int rowsAffected = _context.Database
    .ExecuteSqlCommand("sp_InsertTrackingInfo {0}", id);

如果它执行选择语句,则需要执行查询,因为它是延迟(延迟)执行,直到 某事 需要它。

var items = _context.Database
    .SqlQuery<T>("sp_InsertTrackingInfo {0}", id)
    .ToArray(); // or FirstOrDefault() or Any() etc

【讨论】:

  • 第一个会这样做。非常感谢:)
猜你喜欢
  • 2017-05-19
  • 2013-11-23
  • 1970-01-01
  • 1970-01-01
  • 2010-09-14
  • 1970-01-01
相关资源
最近更新 更多