c# - 将 Linq 查询与 Entity Framework 一起使用时引发异常

标签 c# winforms linq listbox

我从这个问题中删除了大量文本,因为我觉得它需要更简洁。 - 塞尔格

这就是我想要做的。用户选择一个州,然后组合框加载该州的城市,然后当用户选择一个城市时,列表框加载该城市的所有项目。

当运行应该将项目加载到 ComboBox 的方法时,我收到此错误:

Exception has been thrown by the target of an invocation. Inner Exception is: "{"Specified cast is not valid."}"valid."}"

这是导致异常的方法:

private void LoadProjectsToListBox(long idCity)
{
    ProjectRepository projectRepo = new ProjectRepository();    

    //This line causes the error.
    var projects = projectRepo.FindAllProjects().Where(c => c.IDCity == 1).ToList();
}

在 Linq 查询中,您会看到我正在与硬编码数字进行比较。 1,是具有项目的城市的有效 ID,因此它应该可以工作。仅当我为 Linq 查询提供具有项目的城市 ID 时才会引发异常。因此,当查询返回结果时,似乎会引发错误。

下面是我用来生成 Project 和 City 表的 SQL 语句:

create table City
(
    ID integer primary key autoincrement,
    Name string,
    IDState integer references State(ID)
);

create table Project
(
    ID integer primary key autoincrement,
    Name string,
    StartDate text,
    IDManager integer references Manager(ID),
    IDCity integer references City(ID),
    IDDepartment integer references Department(ID),
    ContactNumber string,
    Description string
);

令我感到奇怪的是,使用完全相同的模式和访问代码 来显示部门列表(只是我数据库中的另一个表)一切都按预期进行。例如,这是我现在加载部门的方式,只是为了测试:

private void LoadProjectsToListBox(long idCity)
{
    ProjectRepository projectRepo = new ProjectRepository();
    DepartmentRepository departmentRepo = new DepartmentRepository();

    //Doesn't work - raises exception.
    var projects = projectRepo.FindAllProjects().Where(c => c.IDCity == 1).ToList();

    //Works exactly as expected.
    var deps = departmentRepo.FindAllDepartments().Where(c => c.IDParentDepartment == 7).ToList();

    lstProjects.Items.Clear();
    foreach (var item in deps)
    {
        lstProjects.Items.Add(item.Name);
    }
}

编辑:

FindAllDepartments()、FindAllCities()、FindAllProjects() 方法本质上是相同的。

DocumentsDBEntities db = new DocumentsDBEntities();

public IQueryable<Project> FindAllProjects()
{
    return db.Projects;
}

public IQueryable<City> FindAllCities()
{
    return db.Cities;
}

public IQueryable<Department> FindAllDepartments()
{
    return db.Departments;
}

如前所述,部门获取工作;项目获取导致异常。

编辑 3:

我修好了!问题在于在项目表中使用“文本”数据类型。如果我将该列的数据类型从“文本”更改为“字符串”,它就可以完美运行。谁能告诉我为什么?

最佳答案

上周我遇到了完全相同的问题!在我的例子中,问题是我拉到 .dbml 文件的一些表有不同的数据库连接(测试与生产),即使表(概念上)相同,也无法转换表将“db1.table1”键入“db2.table1”。我不知道这是否是您问题的根源,但我希望这能以某种方式提供帮助。确保我的所有表都来自完全相同的数据库连接是我解决问题的方法。

关于c# - 将 Linq 查询与 Entity Framework 一起使用时引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4074058/

相关文章:

c# - 在 Epplus (C#) 中创建没有基表的数据透视表

c# - 将 WCF 数据服务与 Windows 应用程序结合使用

c# - .NET winforms 应用程序在不使用 ClickOnce 的情况下更新自身的最佳方式是什么?

C# 遍历 3D 数组的最快维度

c# - 当位掩码(标志)枚举变得太大时该怎么办

c# - jQuery AJAX 文件上传到 WCF Web 服务在大数据上失败

c# - Winforms 基于角色的安全限制

c# - 在 Entity Framework linq 中两次包含相同字段时的行为

具有动态 LINQ 的 C# bool 逻辑?

c# - 在查看 ANTS 分析器时,FirstOrDefault 明显快于 SingleOrDefault