我需要只使用存储过程来完成任务。
在我的应用程序中,我有名为"Document"one_answers"DocumentInfo"的模型,它们指的是mysql表。例如,我得到了最简单的存储过程来按文件名获取documentInfos列表
SQL:
CREATE PROCEDURE `GetDocumentByName` (DocName varchar(255))
BEGIN
Select * from GetAllDocuments where DocumentName like DocName;
END$$
C#:
public List<DocumentsInfo> GetDocumentByName(string Filename)
{
return db.DocumentsInfo.FromSql("CALL GetDocumentByName({0})", Filename).ToList();
}
正如您所看到的,我使用的是db-这就是dbContext。DocumentsInfo这是我的模型,我返回了DocumentsInfos对象的列表。但如果我不需要返回整个对象,而只返回一列,该怎么办?
现在我需要做同样的事情,但使用"Document",但只是这次我只需要使用一个字段-DocumentBody,即BLOB
SQL:
CREATE PROCEDURE `GetDocumentBodyById` (DocumentBodyID INT(11))
BEGIN
Select DocumentBody from Document where idDocumentBody = DocumentBodyID;
END$$
C#:
var test = db.FromSql("CALL GetDocumentBodyById({0})", DocumentID).FirstOrDefault();
给我一个错误:
"DBContext"不包含"FromSql"的定义,并且没有可访问的扩展方法"FromSql"接受的第一个参数未能找到类型"DBContext"(是否缺少using指令或程序集引用?(
还尝试使用此选项:
var test = db.Database.SqlQuery<object>("CALL GetDocumentBodyById({0})", DocumentID).FirstOrDefault();
但收到新错误:
"数据库立面"不包含"SqlQuery"的定义,并且没有可访问的扩展方法"SqlQuery">
如何调用只返回一个值而不返回整个模型对象的存储过程?使用.net核心有可能吗?
对于FromSql
,它与Query
一起使用,您可以为返回结果定义一个新的模型。
public class ResultDto
{
public string Name { get; set; }
}
在OnModelCreating
中定义Query
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Query<ResultDto>();
}
用途:
var result = _context.Query<ResultDto>().FromSql("exec GetDocumentBodyById {0}", 1).ToList();