2011-12-21 37 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();