在实体框架中查询外键填充组合框

时间:2018-08-27 14:13:59

标签: c# entity-framework

我有ComboBox个省:

public Form1()
{
    InitializeComponent();
    using (AbEntities c = new AbEntities())
    {
        comboBox1.DataSource = c.tbl_Province.ToList();
        comboBox1.ValueMember = "ID";
        comboBox1.DisplayMember = "Province";
    }
}

现在我想在另一个组合框中列出每个省的城市。

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    if (comboBox1.SelectedValue.ToString() != null)
    {
        int pvc = Convert.ToInt32(comboBox1.SelectedValue.ToString());
        string sqlString = "SELECT ID,City FROM tbl_City Where ProvinceID = pvc"

        using (AbEntities c = new AbEntities())
        {
            comboBox2.DataSource = c.tbl_City.ToList();
            comboBox2.ValueMember = "ID";
            comboBox2.DisplayMember = "City";
        }
    }
}

我写了以下查询。但是城市没有被过滤

2 个答案:

答案 0 :(得分:1)

您需要查询DbSet,例如:

c.tbl_City.Where(c => c.ProvinceID == pvc).ToList();

进一步:

SQL语句和过滤器之间没有关系。

您可能想阅读有关linq的信息,

以下是有关EF的更多信息:http://www.entityframeworktutorial.net/querying-entity-graph-in-entity-framework.aspx

答案 1 :(得分:1)

我在您的代码中看不到任何过滤。也许您应该应用这样的内容:

comboBox2.DataSource = c.tbl_City.Where(x=>x.ProvinceID == pvc).ToList();

说明:

您的代码中的松散SQL查询字符串没有应用程序。由于您的帖子标有entity-framework,因此我假设AbEntitiesDataContext。 在这种情况下,tbl_City实现了IQueryable接口,并允许您直接在代码中调用Where。在此示例中,我使用了方法语法。 ToList()调用将执行查询并具体化结果。 这也可以使用查询语法来完成:

comboBox2.DataSource = (from   x in c.tbl_City
                        where  x.ProvinceID == pvc
                        select x).ToList();
相关问题