如何从实体框架中的两个关联表中获取数据

时间:2015-07-27 10:16:49

标签: c# asp.net entity-framework asp.net-mvc-4 linq-to-entities

我有两个名为Places的地方和经历有一对多的关系。我想以下列格式从这些表中获取数据 -

[
 {
"PlaceId": 1,
"PlaceName": "Agra",
"Experience": [
  {
    "ExperienceId": 1,
    "ExperienceName": "TajMahel"
  },
  {
    "ExperienceId": 2,
    "ExperienceName": "AgraFort"
  }
   ]
  }
]

所以我正在编写这样的查询但是没有用。我不知道如何编写嵌套查询。

var exp=from log in db.Places where(log.IsActive==true)
select new
{
    log.Id,
    from log1 in log.Experiences where(log1.LanguageId==1) select new {log1.Id,log1.Title}
};

1 个答案:

答案 0 :(得分:0)

你可以试试这样的事情

     var exp = from log in db.Places
                      where log.IsActive==true
                      select new
                          {
                              logId= log.Id,,
                              experiences = from exp in log.Experiences 
                                         where(log1.LanguageId==1)
                                         select new
                                             {
                                                 id=log1.Id,
                                                 title=log1.Title
                                             }
                          };

Anonymous Type Projection

Linq Projection