Linq to Entity實作(參考http://msdn.microsoft.com/zh-tw/library/bb399182.aspx)

Linq to Entity實作(參考http://msdn.microsoft.com/zh-tw/library/bb399182.aspx)

(新增專案)

image

(新增EDM實體資料模組)

image

image image

image image

image

(畫面)

image

 

   1:  using System.Data.Objects;//需要用到ObjectQuery
   2:   
   3:  namespace LinQ_to_Entity
   4:  {
   5:      public partial class fmMain : Form
   6:      {
   7:          private SchoolEntities schoolEntity;
   8:          public fmMain()
   9:          {
  10:              InitializeComponent();
  11:   
  12:              schoolEntity = new SchoolEntities();
  13:          }
  14:   
  15:          private void fmMain_Load(object sender, EventArgs e)
  16:          {
  17:              var query = from q in schoolEntity.Departments.Include("Courses")
  18:                                  select q;
  19:              //ObjectQuery<T>.Include 方法(指定要包含在查詢結果中的相關物件)
  20:              //※所以在查詢Departments時,會順便查詢Course(存放在Departments.Course的集合內)
  21:              cmbDepartment.DisplayMember = "Name";
  22:              cmbDepartment.DataSource = ((ObjectQuery)query).Execute(MergeOption.AppendOnly);
  23:              //MergeOption 列舉型別(指定載入物件內容中的物件如何與已經位於物件內容中的物件合併)
  24:          }
  25:   
  26:          private void cmbDepartment_SelectedIndexChanged(object sender, EventArgs e)
  27:          {
  28:              if (cmbDepartment.SelectedItem != null)
  29:              {
  30:                  Department department = (Department)cmbDepartment.SelectedItem;
  31:                  //因為在查詢Departments就已經把Courses連帶查詢好了,所以就只要指定department的Coures集合
  32:                  grdCourses.DataSource = department.Courses;
  33:              }
  34:          }
  35:   
  36:          private void btnSave_Click(object sender, EventArgs e)
  37:          {
  38:              schoolEntity.SaveChanges();//儲存異動資料
  39:          }
  40:      }
  41:  }

(執行)

image