我有两种替代方法可以从数据库中检索数据。
1) 使用 Ado.net
public List<Customer> GetDetail()
{
SqlConnection connectionstring = new SqlConnection(connectionstring goes on..);
List<Customer> custList = new List<Customer>();
connectionstring.Open();
string query = "select * from Customer";
SqlCommand command = new SqlCommand(query, connectionstring);
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Customer cust = new Customer();
cust.Name = reader["Name"].ToString();
cust.UserName = reader["UserName"].ToString();
cust.CountryId = reader["CountryId"].ToString();
cust.EmailId = reader["EmailId"].ToString();
cust.PhoneNo = reader["PhoneNo"].ToString();
custList.Add(cust);
}
}
connectionstring.Close();
return custList;
}
2)使用实体框架
public List <Customer> GetDetail()
{
DataTable dt = new DataTable();
List<Customer> CustomerList = new List<Customer>();
CustomerEntities context = new CustomerEntities(GetConnectionObject());
foreach (Customer cus in context.Customers)
{
CustomerList.Add(cus);
}
return CustomerList;
}
我正在使用 jquery ajax 调用调用控制器方法,它调用上述方法。
$.ajax({
type: "POST",
url: "/Customer/GetDetails",
dataType: 'json',
async: false,
cache: false,
success: function (data) {
alert("success");
$.each(data, function (index, customer) {
alert(customer.Name + " " + customer.UserName);
});
},
error: function (jqXHR, textStatus, errorThrown) {
if (typeof (console) != 'undefined') {
alert("oooppss");
}
else { alert("something went wrong"); }
}
});
如果是普通的 ado.net 代码,它成功地检索数据并调用 ajax 成功函数。
但是,如果是实体框架方法,即使它正在检索数据(调试时,我可以在 customerList 对象中看到结果数据),也不会调用 ajax 成功函数。相反,错误函数被调用。errorThrown 是“内部服务器错误”。
为什么?实体框架有什么问题?
谁能为此提供解决方案..?