我正在使用Winforms,C#,VS2010和Entity Framework编写一个简单的第一个应用程序。基本上,我有一个丰富的数据库,我正在点击,我已经设置了框架,成功地足以用工作订单表的子集填充DataGridView控件。
现在,我想在表单(“cbProjectID”)上放置一个组合框,其值为ProjectID,DisplayValue为ProjectNbr。我只想将项目放在与WorkOrders相关的组合框列表中,并且只有该组中的唯一ProjectID(项目可能有几十个工单......)
我假设我需要使用LINQ从EF生成列表。我在LINQ上很新,而且我不知道......到目前为止,这是我的代码......
using System;
using CPASEntityFramework;
using System.Data.Entity;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace BrowseWorkOrders
{
public partial class BrowseWOs : Form
{
public BrowseWOs()
{
InitializeComponent();
}
private void BrowseWOs_Load(object sender, EventArgs e)
{
var context = new CPASEntities();
var query = context.tblWorkOrders.Where(c => c.ProjectID==8);
tblWorkOrderBindingSource.DataSource = query.ToList();
// Now, I want to load up the Combo Box with all the projects in the Work Order Table
}
}
}
我一直在试图找到一种我理解的方法,但是我失败了。也许有人可以帮助我。这是我的数据源(我假设我不应该使用tblProject,而是使用tblWorkOrder中的tblProject来获取我的子集...)
任何帮助和/或指导将不胜感激。
现在是代码......
namespace BrowseWorkOrders
{
public partial class BrowseWOs : Form
{
public BrowseWOs()
{
InitializeComponent();
}
private void BrowseWOs_Load(object sender, EventArgs e)
{
// Following loads up all Projects into the cbProjectID Combo Box
var context = new CPASEntities();
var PrID = context.qryProjectIDNbrDescs.ToList();
cbProjectID.DataSource = PrID;
cbProjectID.ValueMember = "ID";
cbProjectID.DisplayMember = "ProjectNbr";
}
private void cbProjectID_SelectedIndexChanged(object sender, EventArgs e)
{
var context = new CPASEntities();
var query = context.tblWorkOrders.Where(c => c.ProjectID == (int)cbProjectID.SelectedValue).ToList();
tblWorkOrderBindingSource.DataSource = query;
}
}
}
答案 0 :(得分:4)
您需要顶部的tblProject,因为另一个仅适用于单个WorkOrder。但是,您需要使用至少具有WorkOrder的人筛选列表:
var projects = context.tblProjects.Where(p => p.tblWorkOrders.Any()).ToArray();
cbProjectID.DataSource = projects;
cbProjectID.ValueMember = "ProjectID";
cbProjectID.DisplayMember = "ProjectNbr";