实体框架中的查询

时间:2011-05-27 12:39:21

标签: asp.net asp.net-mvc

在返回视图

之前,

必须在JobSearchAgentID上应用if条件

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);

2 个答案:

答案 0 :(得分:1)

你可以选择内联条件

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

答案 1 :(得分:0)

可以将查询重写为:

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.ObjectModel命名空间中)。无论如何我已经更新了我的答案。这适用于您的场景。 由于上面的linq查询的结果是一个集合(IEnumerable),因此您需要遍历它以获取所需的数据。希望它能回答你的问题。