【问题标题】:Error in LINQ query when referecing value in combo box引用组合框中的值时 LINQ 查询出错
【发布时间】:2016-03-22 20:23:36
【问题描述】:

我在使组合框正确级联时遇到了一些问题。我首先使用带有实体框架代码的 WinForms,我正在努力让第二个组合框正常工作。我的类别模型如下所示:

public class Category
{
    [Key]
    public int ID { get; set; }

    [Required]
    public string CategoryName { get; set; }
}

我的子类别如下所示:

public class SubCategory
{
    [Key]
    public int ID { get; set; }

    public virtual Category Category { get; set; }

    [Required]
    public string SubCategoryName { get; set; }
}

在类别组合框的 SelectedIndexChanged 事件中,我尝试了以下代码:

cmboSubCategory.DataSource = ( from sc in db.SubCategories.AsEnumerable()
                                where sc.Category == int.Parse( cmboCategory.SelectedValue.ToString() )
                                select sc ).ToList();

但是编译器告诉我

Operator '==' cannot be applied to operands of type 'Category' and 'int'

在数据库中查找 SubCategories 表中的 FK 字段名为 Category_ID 但是当我尝试使用此字段名称时,编译器会抱怨该字段不存在。如何使用模型中定义的虚拟字段名称进行查找?我做错了什么?

【问题讨论】:

    标签: c# winforms entity-framework linq combobox


    【解决方案1】:

    无法检查 Category 对象与 int 的相等性。使用 id 检查它们是否相等。

    将 ID 属性添加到 sc.Category

    cmboSubCategory.DataSource = ( from sc in db.SubCategories.AsEnumerable()
                                where sc.Category.ID == int.Parse( cmboCategory.SelectedValue.ToString() )
                                select sc ).ToList();
    

    【讨论】:

      【解决方案2】:

      不能将 Category 对象与 int 相等。使用 id 检查是否等于。

      我觉得你不见了.ID

      where sc.Category.ID == int.Parse( cmboCategory.SelectedValue.ToString() )

      【讨论】:

        猜你喜欢
        • 2013-08-11
        • 1970-01-01
        • 1970-01-01
        • 2010-10-04
        • 1970-01-01
        • 2011-05-05
        • 1970-01-01
        • 2010-09-19
        • 1970-01-01
        相关资源
        最近更新 更多