【问题标题】:How to bind an entity framework object to a listview如何将实体框架对象绑定到列表视图
【发布时间】:2012-08-12 18:48:56
【问题描述】:

第一次在这里提问,请大家帮我表达一下意思。

首先我使用了一个实体框架,我想进行一个查询,从 3 个表中检索数据,然后将结果绑定到列表视图,这里的问题是页面上没有任何内容。这就是我做的:

ITIEntities MyContext = new ITIEntities();
var Courses = MyContext.Courses;
var Instructors = MyContext.Instructors;
var Ins_Courses = MyContext.Ins_Course;
var Query= from Crs in Courses
           from Ints in Instructors
           from Instructor_courses in Ins_Courses
           where Crs.Crs_Id==Instructor_courses.Crs_Id
           && Instructor_courses.Ins_Id== Ints.Ins_Id
           select new 
           {
               Name=  Ints.Ins_Name,
               Salary=Ints.Salary,
               ListOfCourses=Crs.Crs_Name,
           };
MyListView.DataSource = Query;
MyListView.DataBind();            

MyContext.SaveChanges();

【问题讨论】:

  • 请显示您的标记。还有为什么要在选择后保存对上下文的更改?

标签: asp.net .net entity-framework


【解决方案1】:

这里的问题是可枚举类型变量 Query,因此如果要将结果绑定到列表视图,则必须为要显示的每一列定义具有 getter 和 setter 属性的实体公共类。

public Class ClassNameEntity
{

public string Name {get; set;}

}

在 linq 查询中使用以下内容

 select new ClassNameEntity
{
Name= Ints.Ins_Name

}.ToList();

这将返回您定义的类对象列表的列表,因此直接绑定上层查询的结果。

ITIEntities MyContext = new ITIEntities();
            var Courses = MyContext.Courses;
            var Instructors = MyContext.Instructors;
            var Ins_Courses = MyContext.Ins_Course;
            List<ClassNameEntity> Query= from Crs in Courses
                       from Ints in Instructors
                       from Instructor_courses in Ins_Courses
                       where Crs.Crs_Id==Instructor_courses.Crs_Id
                       && Instructor_courses.Ins_Id== Ints.Ins_Id
                       select new ClassNameEntity
                       {
                           Name=  Ints.Ins_Name,
                           Salary=Ints.Salary,
                           ListOfCourses=Crs.Crs_Name,
                       }.ToList();
            MyListView.DataSource = Query;
            MyListView.DataBind();            

                MyContext.SaveChanges();

【讨论】:

  • 这是唯一的办法吗兄弟?
猜你喜欢
  • 2011-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多