我试图填充一个GridView
使用Entity Frameworkm的方法,但是每次遇到以下错误时:
“对象'COSIS_DAL.MemberLoan'上的属性访问器'LoanProduct'引发以下异常:ObjectContext实例已被处置,不能再用于需要连接的操作。”
我的代码是:
public List<MemberLoan> GetAllMembersForLoan(string keyword)
{
using (CosisEntities db = new CosisEntities())
{
IQueryable<MemberLoan> query = db.MemberLoans.OrderByDescending(m => m.LoanDate);
if (!string.IsNullOrEmpty(keyword))
{
keyword = keyword.ToLower();
query = query.Where(m =>
m.LoanProviderCode.Contains(keyword)
|| m.MemNo.Contains(keyword)
|| (!string.IsNullOrEmpty(m.LoanProduct.LoanProductName) && m.LoanProduct.LoanProductName.ToLower().Contains(keyword))
|| m.Membership.MemName.Contains(keyword)
|| m.GeneralMasterInformation.Description.Contains(keyword)
);
}
return query.ToList();
}
}
protected void btnSearch_Click(object sender, ImageClickEventArgs e)
{
string keyword = txtKeyword.Text.ToLower();
LoanController c = new LoanController();
List<COSIS_DAL.MemberLoan> list = new List<COSIS_DAL.MemberLoan>();
list = c.GetAllMembersForLoan(keyword);
if (list.Count <= 0)
{
lblMsg.Text = "No Records Found";
GridView1.DataSourceID = null;
GridView1.DataSource = null;
GridView1.DataBind();
}
else
{
lblMsg.Text = "";
GridView1.DataSourceID = null;
GridView1.DataSource = list;
GridView1.DataBind();
}
}
错误是提到的LoanProductName
列Gridview
。提及:我正在使用C#,ASP.net,SQL-Server 2008作为后端数据库。
我是实体框架的新手。我不明白为什么会收到此错误。有人可以帮我吗?
db.MemberLoans.Include("LoanProduct").OrderByDescending()
检查语法,因为我面前没有VS。
db.MemberLoans.Include("LoanProduct").Include("SomeOtherTable)
。检查@Tragedian和@lazyberezovsky的答案
query.Include("SomeOtherTable")