using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using Dapper;
namespace Calculate.Models
{
public class SelectedDetailsGetter
{
SqlConnection con = new SqlConnection("Data Source=CHANDAKG-01-L\\SQLEXPRESS;initial catalog=Calculator;integrated security=true");
public IEnumerable<SelectedDetails> GetSelectedDetails(string Name)
{
string query = "SELECT * FROM DataNorm WHERE Provider=@name AND year(DateMonth)=2014";
var result = con.Query<SelectedDetails>(query,new { name = Name });
return result;
}
}
}
此Query始终返回null。有什么不对??任何人都可以告诉使用SingleOrDefault()
答案 0 :(得分:1)
首先,如果存在,SingleOrDefault()函数将始终返回一个唯一的寄存器。人们在查询结果将多次返回行时使用,但在这种情况下只是第一个问题。
现在,解决你的问题
始终使用&#34;使用&#34;使用连接,这是保证您永远不会忘记关闭和处置打开的连接的最佳方式。
在实例化对象Connection之后,您总是需要打开连接。
试试这个:
public IEnumerable<SelectedDetails> GetSelectedDetails(string Name)
{
using (var con = new SqlConnection("Data Source=CHANDAKG-01-L\\SQLEXPRESS;initial catalog=Calculator;integrated security=true"))
{
con.Open();
string query = @" SELECT *
FROM DataNorm
WHERE Provider= @name
AND year(DateMonth) = 2014 ";
var result = con.Query<SelectedDetails>(query, new { name = Name });
return result;
}
}
答案 1 :(得分:0)
来自github:
注意:所有扩展方法都假设连接已打开,如果连接已关闭,它们将失败。