【问题标题】:How to write Subquery in Entity Framework using Linq如何使用 Linq 在实体框架中编写子查询
【发布时间】:2011-12-21 05:58:59
【问题描述】:

您好,我想在 LINQ 实体框架中使用这个......

select Empame,EmpSalary,EmpDepartment,(select CountryName from Countries c where c.ID = Employees.EmpCountry) as Country,(select StateName from dbo.States c where c.ID = Employees.EmpState)as States from Employees

我试过这个它给出的错误在这里输入代码

    public ActionResult Index()
    {
    var Employee = (from e in _db.Employee
    select new 
    {
    Empame = e.Empame,
    EmpSalary = e.EmpSalary,
    EmpDepartment = e.EmpDepartment,
    EmpCountry = (from c in _db.Country
    where (c.ID.ToString() == e.EmpCountry)
    select c),
    EmpState = (from s in _db.States
    where (s.ID.ToString() == e.EmpState)
    select s)});
    return View(Employee);
}

无法将类型“System.Linq.IQueryable”隐式转换为“字符串”

【问题讨论】:

    标签: linq entity-framework


    【解决方案1】:
    from e in Employees 
    from c in Countries
    from s in States
    where c.ID == e.EmpCountry
    where s.ID == e.EmpState
    select new {
        EmpName = e.EmpName,
        EmpSalary= e.EmpSalary,
        EmpDepartment= e.EmpDepartment,
        Country = c.Single(),
        State = s.Single()
    }
    

    但更好的方法是让您的模型具有国家和州表的导航属性。如果您使用外键从数据库生成 EDMX 文件,导航属性将自动创建。这意味着您将能够简单地使用:

    from e in Employees.Include(em=>em.Country).include(em=>em.State)
    select e;
    

    您得到的实际错误是因为您的视图需要一个字符串而不是 IQueriable。要更改此设置,请确保您在视图中指定模型类型

    【讨论】:

    • 来自 e 来自 c 国家的雇员来自 s 的国家 where c.ID.ToString == e.EmpCountry where s.ID.ToString==e.EmpStateselect new { EmpName = e.EmpName, EmpSalary= e.EmpSalary,EmpDepartment= e.EmpDepartment, Country = c.Single(),State = s.Single() } System.InvalidOperationException: 传入字典的模型项的类型为 'System.Data.Entity.Infrastructure .DbQuery1[<>f__AnonymousType46[System.String,System.Double,System.String,System.String,System.String,System.String]]',但此字典需要“System.Collections.Generic”类型的模型项。 IEnumerable`1
    • "您得到的实际错误是因为您的视图需要一个字符串而不是 IQueriable。要更改这一点,请确保您在视图中指定模型类型"
    【解决方案2】:

    似乎您正在尝试返回非具体化查询。尝试添加.Single(), .FirstOrDefault()等:

    var Employee = (from e in _db.Employee
        select new 
        {
        Empame = e.Empame,
        EmpSalary = e.EmpSalary,
        EmpDepartment = e.EmpDepartment,
        EmpCountry = (from c in _db.Country
        where (c.ID.ToString() == e.EmpCountry)
        select c),
        EmpState = (from s in _db.States
        where (s.ID.ToString() == e.EmpState)
        select s)}).FirstOrDefault();
    

    【讨论】:

      猜你喜欢
      • 2016-06-05
      • 1970-01-01
      • 2020-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-01
      • 2021-12-25
      • 1970-01-01
      相关资源
      最近更新 更多