如何使用Linq在Entity Framework中编写子查询

时间:2011-12-21 05:58:59

标签: linq entity-framework

您好我想在LINQ Entity框架中使用它.......

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'隐式转换为'string'

2 个答案:

答案 0 :(得分:0)

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()
}

但更好的方法是让您的模型具有Country和state表的导航属性。如果使用外键从DB生成EDMX文件,将自动创建导航属性。这意味着您只需使用:

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

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

答案 1 :(得分:0)

好像您正在尝试返回非实体化查询。尝试添加.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();