使用实体框架5和MVC 4自定义查询
本文关键字:MVC 自定义 查询 实体 框架 | 更新日期: 2023-09-27 18:17:49
目标
在使用c#的应用程序中自定义¹查询。. NET + MVC 4 +实体框架+ MySQL.
我想执行查询并将结果返回给视图,但我不知道该怎么做。
我有什么
下面的查询返回一些productName
, minProductprice
, maxProductPrice
(我想在我的视图中显示):
SELECT MIN(`map`.`Product_Price`) as `minProductPrice`,
MAX(`map`.`Product_Price`) as `maxProductPrice`,
`pr`.`Product_Name` as `productName`
FROM `bm_market_products` `map` join
`bm_products` as `pr`
on map`.`Product_Id` = `pr`.`Product_Id`
group by `map`.`Product_Id`
重复的问题吗?
我不这么认为。我发现了这个问题,题目也差不多,但是上下文好像不一样。
那么,我该如何解决我的问题呢?
详细信息¹:"custom"表示实体框架创建的默认CRUD之外的东西。我之前展示的查询在默认情况下没有执行,我想执行它。
提前感谢!
为什么你不能使用SqlDataAdapter和DataSet作为实体框架现在意识到"动态查询",然后你可以在你需要的地方显示它们。
希望能有所帮助。
我使用ObjectContext
的ExecuteStoreQuery
方法(DbContext
派生自直接执行SQL)。我不确定这是最好的方法,但经过多次搜索,这是我能找到的最好的方法:
public class ResultObject
{
public string ProductName { get; set; }
public decimal MinProductPrice { get; set; }
public decimal MaxProductPrice { get; set; }
}
//Within your Control or somewhere common
public IList<TResult> ExecuteSql<TResult>(string sql)
{
var results = ((IObjectContextAdapter)DbContext).ObjectContext.ExecuteStoreQuery<TResult>(sql);
return results;
}
//Then, when you need the results, call the ExecuteSql method:
var productInfo = ExecuteSql<ResultObject>(mySql);
所有关于内联sql的标准警告都适用,包括清除用户输入数据,以及它是一个坏主意(您可能应该考虑使用存储过程)。这也适用于存储过程,因为如果需要,可以将Parameters集合传递给ExecuteStoreQuery
方法。
在Brian S的帮助下,我可以得出更简洁的方法是使用存储过程。我是初学者,我在MySQL文档的"使用存储例程"帖子中找到了解决方案。
对了,谢谢你的帮助。更新v1
Coskun Sunali的"使用实体框架和MySQL存储过程查询MySQL"是一篇教授使用EF +存储过程的好方法的文章。对于初学者来说,这是一个很好的解决方案!