使用Linq从两个表中选择值

本文关键字:两个 选择 Linq 使用 | 更新日期: 2023-09-27 18:03:12

大家好,我知道这个问题已经问过很多次了,但是我还是想不明白

如何从多个表中选择值

我做了这两个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是我用来在secondblockd中获取值(Name)的。verticalIdstageManagerVerticals的主键和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();

使用Linq从两个表中选择值

尝试在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 };
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();

你可以使用导航属性,

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