查询在实体框架

问题描述:

有返回视图查询在实体框架

var res = (from results in db.JobSearchAgents 
          where results.SiteID == 110 && results.UserID == sess 
          select results).AsEnumerable().Select(results => new Agentlist 
          { 
           JobSearchAgentID = results.JobSearchAgentID.ToString(), 

           EmailAddress = results.EmailAddress, 
           Keywords = results.Keywords, 


           Country = results.Country, 

           zipcode = results.ZipCode, 
           miles = results.Miles.ToString() 

          }); 

      return View(res); 
+6

你的问题是什么? – 2011-05-27 12:41:01

,你可以去内联状态

(from results in db.JobSearchAgents 
          where results.SiteID == 110 && results.UserID == sess 
          select results).AsEnumerable().Select(results => new Agentlist 
          { 
           //it is just an example 
           JobSearchAgentID =JobSearchAgentID!=null? results.JobSearchAgentID.ToString():[somthing else], 

           EmailAddress = results.EmailAddress, 
           Keywords = results.Keywords, 

           //another example 
           Country = String.IsNullOrEmpty(results.Country)?"No Country":results.Country, 
           //the last example 
           zipcode =results.Country=="United States"? "123": results.ZipCode, 
           miles = results.Miles.ToString() 

          }); 

      return View(res); 
+0

我必须检查res.country ==“”那么我能做什么 – iProgrammer 2011-05-27 13:57:57

+0

你仍然可以使用内联if。我已编辑我的答案 – 2011-05-27 14:02:35

+0

我必须检查res.country ==“有限状态” – iProgrammer 2011-05-27 14:05:21

查询可以改写为之前JobSearchAgentID如果条件适用于:

var res = from results in db.JobSearchAgents 
where results.SiteID == 110 && results.UserID == sess 
select new Agentlist 
{ 
    JobSearchAgentID = results.JobSearchAgentID.ToString(), 
    EmailAddress = results.EmailAddress, 
    Keywords = results.Keywords, 
    Country = results.Country, 
    zipcode = results.Country=="United States" ? "123" : results.ZipCode, 
    miles = results.Miles.ToString() 
}); 
string country = string.Emtpy; 

foreach (var agentLst in res) 
{ 
    country = agentLst.Country;  
} 

我最后的回答是在MVVM的上下文中,我们通常使用ObservableCollection(存在于System.Collections.Ob jectModel命名空间)。无论如何,我已经更新了我的答案。这将在你的情况下工作。 由于上面的linq查询的结果是一个集合(IEnumerable),因此您需要遍历它以获取所需的数据。希望它能回答你的问题。

+0

它缺少程序集引用 – iProgrammer 2011-05-28 05:00:28

+0

它显示类型或名称空间可观察集合无法找到 – iProgrammer 2011-05-28 05:12:35

+0

它显示错误只有赋值,调用增量,递减,新的对象表达式可以用作语句 – iProgrammer 2011-05-28 05:21:42