【发布时间】:2017-10-11 15:11:07
【问题描述】:
ALTER PROCEDURE [dbo].[SearchMovies]
--@Year int = null,
@CategoryIds varchar(50) = null,
@Keywords nvarchar(4000) = null,
@PageIndex int = 1,
@PageSize int = 2147483644,
@TotalRecords int = null OUTPUT
As ...
EF 存储库:
public class EFRepository<T> : IRepository<T> where T : BaseEntity
{
private readonly ApplicationDbContext _ctx;
private DbSet<T> entities;
string errorMessage = string.Empty;
public EFRepository(ApplicationDbContext context)
{
this._ctx = context;
entities = context.Set<T>();
}
...
public IQueryable<T> ExecuteStoredProcedureList(string commandText, params object[] parameters)
{
_ctx.Database.ExecuteSqlCommand(commandText, parameters);
return entities.FromSql(commandText, parameters);
}
}
我这样称呼它:
var pCategoryIds = new SqlParameter()
{
ParameterName = "@CategoryIds",
Value = commaSeparatedCategoryIds,
DbType = DbType.String
};
var pKeywords = new SqlParameter()
{
ParameterName = "@Keywords",
DbType = DbType.String,
Value = name
};
var pPageIndex = new SqlParameter()
{
ParameterName = "@PageIndex",
DbType = DbType.Int32,
Value = pageIndex
};
var pPageSize = new SqlParameter()
{
ParameterName = "@PageSize",
DbType = DbType.Int32,
Value = pageSize
};
var pTotalRecords = new SqlParameter();
pTotalRecords.ParameterName = "@TotalRecords";
pTotalRecords.Direction = ParameterDirection.Output;
pTotalRecords.DbType = DbType.Int32;
var query1 = _ctx.Database.ExecuteSqlCommand("dbo.[SearchMovies] " +
"@CategoryIds, @Keywords, @PageIndex, @PageSize, @TotalRecords OUTPUT",
pCategoryIds, pKeywords, pPageIndex, pPageSize, pTotalRecords);
var query2 = _ctx.Set<MovieItem>.FromSql("dbo.[SearchMovies] " +
"@CategoryIds, @Keywords, @PageIndex, @PageSize, @TotalRecords OUTPUT",
pCategoryIds, pKeywords, pPageIndex, pPageSize, pTotalRecords);
query1 确实得到了输出pTotalRecords,但没有返回值,第二个query2 得到返回值但没有输出参数。
在 EF 6 中,我们曾经有 SqlQuery 在一个命令中执行这两个操作,我如何在 EF 核心中执行相同的操作?
更新:
我暂时运行了 2 个查询,一个用于获取输出参数,一个用于结果集。
public IQueryable<T> ExecuteStoredProcedureList(string commandText, params object[] parameters)
{
_ctx.Database.ExecuteSqlCommand(commandText, parameters);
return entities.FromSql(commandText, parameters);
}
【问题讨论】:
-
您的 MovieItem 型号是什么?它是否具有与存储过程返回的完全相同的属性?
-
所以你的意思是使用 Fromsql 它可以返回输出参数? ExecuteSqlCommand 将返回一个整数,在存储过程中,SELECT m.* ... from dbo.MovieItem m 这与 MovieItem 实体完全相同。
-
从 EF Core 1.x 开始,EF Core 仅支持映射到现有实体的结果值,并且该实体中不能缺少任何字段。请参阅EF Core roadmap:非模型类型的原始 SQL 查询允许使用原始 SQL 查询来填充不属于模型的类型(通常用于非规范化视图模型数据)。
-
我没有问题得到上面所说的结果,使用 FromSql 我得到了所有结果,除了 TotalRecords 这是一个行数。而且似乎 EF 核心仍然缺少此功能,因为我已经搜索了几个小时,但没有人为此提供示例。见dotnetthoughts.net/how-to-execute-storedprocedure-in-ef-core
-
@DmitryPavlov 感谢您的信息。好像是这里提到的github.com/aspnet/EntityFrameworkCore/issues/9309 2.0.3 版本的补丁,2.0.3 还没有出来。
标签: c# asp.net-mvc entity-framework asp.net-core entity-framework-core