1

我有两种替代方法可以从数据库中检索数据。

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 是“内部服务器错误”。

为什么?实体框架有什么问题?

谁能为此提供解决方案..?

4

4 回答 4

1

实体框架创建无法序列化的对象(因为它们支持延迟加载,序列化它们实际上可能意味着序列化您的数据库)。要停止此行为,您需要完全关闭延迟加载

            context.ContextOptions.ProxyCreationEnabled = false;
            context.ContextOptions.LazyLoadingEnabled = false;

在进行数据库查询之前插入它,如果问题仍然存在,请在早上给我打电话。

于 2013-03-06T10:50:46.300 回答
0

用这个

 error: function (xhr, ajaxOptions, thrownError) {
    alert(xhr.status);
    alert(thrownError);
    alert(xhr.responseText);
  }

看看会出现什么错误。
可以有很多错误。

于 2013-03-06T07:21:14.500 回答
0

比较两个客户列表集合并检查是否有任何差异......可能是返回对象创建问题......或者在 CustomerEntities 中使用 Using 关键字。

于 2013-03-06T07:18:22.200 回答
0

Json Return 的 EF 创建对象的新代码 您必须首先确保此代码。

            dbcontext.Configuration.ProxyCreationEnabled = false;
            dbcontext.Configuration.LazyLoadingEnabled = false;
于 2019-06-12T12:28:41.417 回答