使用Linq从两个表中选择值

时间:2014-05-14 10:44:55

标签: c# sql linq

嗨,我知道这已被问过很多次,我没有通过我的头颅

How to select Values from several tables

我做了这两个Linq查询

第一

                r = (from d in db.stageManagers 
                 where d.profileID == UserID && d.verticalID == VerticalID 
                 select new StageModels()
                 {
                     UserId = d.profileID,
                     VerticalId = (int)d.verticalID,
                     VerticalStageID = d.stageID
                 }).FirstOrDefault();

第二

            r = (from d in db.stageManagerVerticals
                 where d.ID == r.VerticalId
                 select new StageModels()
                 {
                     VerticalName = d.verticalName
                 }
                 ).FirstOrDefault();

我想将它们作为一个声明,因为它们将数据添加到一个模型,并且它们查询的表格具有 Pk Fk 关系

第一个块中 d.verticalId 是我用来获取 secondblock 中的值(Name), d .verticalId stageManagerVerticals 的主键和 stageManager 中的外键,我如何加入这些查询?

我试过了:

    r = (from d in db.stageManagers  
          join c in db.stageManagerVerticals on d.stageID  equals c.ID
                 where d.profileID == UserID && d.verticalID == VerticalID 
                 select new StageModels()
                 {
                     UserId = d.profileID,
                     VerticalId = (int)d.verticalID,
                     VerticalStageID = d.stageID;
                     VerticalName = c.verticalName
                 }
            ).FirstOrDefault();

3 个答案:

答案 0 :(得分:3)

尝试使用LINQ中的JOIN来从多个表中选择值

例如:

var innerJoinQuery =
    from category in categories
    join prod in products on category.ID equals prod.CategoryID
    select new { ProductName = prod.Name, Category = category.Name };

答案 1 :(得分:1)

var leftOuterJoin=(c in categories
                   join p in products on c.ID equals p.CategoryID into t
                   from temp in t.DefaultIfEmpty()
                   select new { ProductName = p.Name, Category = c.Name }
                  ).ToList();

答案 2 :(得分:1)

您可以使用导航属性

var r = db.stageManagers.Where(x => x.profileID == UserID && x.verticalID == VerticalID).
            Select(
                d => new StageModels() {
                            UserID = d.profileID, 
                            VerticalID = (int)d.verticalID, 
                            VerticalStageID = d.stageID, 
                            VerticalName = d.stageManagerVertical.verticalName
                            }
                ).FirstOrDefault();