【问题标题】:How to read result from raw SQL command如何从原始 SQL 命令读取结果
【发布时间】:2015-06-08 17:26:17
【问题描述】:

问题已更新:

我正在使用 C# + SQL Server + EF6 我需要对没有实体的数据库执行原始 SQL 命令。

string query2 = "SELECT s.Name, t.State, Count(*) [Nb], 
AVG(t.Duration) [Avg], 
MIN(t.Duration) [Min], 
MAX(t.Duration) [Max] from ...";

如何在EF6中得到查询结果?

【问题讨论】:

标签: c# sql-server entity-framework


【解决方案1】:

没有人找到答案。但是投反对票比解决代码问题更容易! 所以,这就是答案,我希望它能帮助遇到同样问题的其他人。 1 / 假设您构建了一个查询,该查询创建了一个表,其中包含名为“Name, State, Nb, Avg, Min, Max 的自定义列:

string query2 = "SELECT s.Name, t.State, Count(*) [Nb], 
AVG(t.Duration) [Avg], 
MIN(t.Duration) [Min], 
MAX(t.Duration) [Max] from ...";

2 / 你必须为从数据库到对象的映射创建一个类:

public class stats
{
    public String Name { get; set; }
    public Int32 State { get; set; }
    public Int32 Nb { get; set; }
    public Int32 Avg { get; set; }
    public Int32 Min { get; set; }
    public Int32 Max { get; set; }
}

3 / 然后你执行查询:

IEnumerable<stats> data = db.Database.SqlQuery<stats>(query2);

db 是扩展 DbContext 的类

【讨论】:

    猜你喜欢
    • 2021-10-12
    • 2014-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-09
    • 1970-01-01
    • 2015-02-02
    相关资源
    最近更新 更多