建立数据模型之后,尝试着写下面这样的一个测试类:
1 using System; 2 using NorthwindModel; 3 4 public partial class DerivedObjectContext : System.Web.UI.Page { 5 protected void Page_Load(object sender, EventArgs e) { 6 NorthwindEntities db = new NorthwindEntities(); 7 8 GridView1.DataSource = db.Products; 9 GridView1.DataBind(); 10 } 11 }
但是运行时报出如下的异常:
using System;
using NorthwindModel;
public partial class DerivedObjectContext : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
NorthwindEntities db = new NorthwindEntities();
GridView1.DataSource = db.Products;
GridView1.DataBind();
}
}
解决方法:加上 .ToList()
GridView1.DataSource = db.Products.ToList();
然后再运行,又报出如下异常:
The type 'Products' is not attributed with EdmEntityTypeAttribute but is contained in an assembly attributed with EdmSchemaAttribute. POCO entities that do not use EdmEntityTypeAttribute cannot be contained in the same assembly as non-POCO entities
解决方法:
关闭数据模型的代码自动生成功能, 将代码改成如下形式:
public partial class Ch13LINQ_DerivedObjectContext : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { NorthwindEntities db = new NorthwindEntities(); GridView1.DataSource = db.Products.ToList(); GridView1.DataBind(); } }
注,上面的代码不用 using NorthwindModel;