2011-12-21 44 views
0
写子查询实体框架

嗨,我想这在LINQ实体框架.......如何使用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 

我想这其givning错误在这里输入代码

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'隐式转换为'字符串'

回答

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

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

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

你得到的实际错误是因为你的视图期望的字符串不是IQueriable。要改变这一点,请确保您在视图中指定模型类型

+0

从E从S其中c.ID.ToString == e.EmpCountry其中s.ID.ToString == e.EmpStateselect新{EmpName = e.EmpName,EmpSalary = e.EmpSalary,EmpDepartment = e.EmpDepartment,Country = c.Single(),State = s.Single()} System.InvalidOperationException:传入字典的模型项目类型为“系统”。 Data.Entity.Infrastructure.DbQuery'1 [<> f__AnonymousType4'6 [System.String,System.Double,System.String,System.String,System.String,System.String]]',但此字典需要一个模型项目类型'System.Collections.Generic.IEnumerable'1 – 2011-12-21 07:22:20

+0

“你得到的实际错误是因为你的视图期望一个字符串不是IQueriable。要改变它,确保你指定了模型类型在“ – 2011-12-21 23:33:31

0

好像您试图返回非物化查询。尝试在员工从C国家在美国加上.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();