将 SQL 转换为具有两个表的 LINQ

本文关键字:两个 LINQ 转换 SQL | 更新日期: 2023-09-27 18:29:27

select ind.desc,ind.number
from int_goals_df idd, goals_df ind
where idd.dld_number = 123456
and ind.number = idd.ind_number
and ind.categorie = 2
order by follownumber

我很难将其转换为 linq,因为它使用两个表。我目前已经用foreach循环紧急解决了这个问题,但对它不满意。

我正在尝试获取与int_goals_df列表匹配的goals_df列表。

任何提示将不胜感激!谢谢!

编辑 - 这是我正在使用的代码:

//get current GoalDefinitions by selected Goal
var currentGoalDefinition = MyAppAppContext.MyAppAppContextInstance.MyAppContext.GoalDefinitions.FirstOrDefault(
    d => d.DLD_GoalDFID == interv.Goal.DLD_GoalenDFID);
// get current intervGoalDefinitions by GoalDefinition
var currentintervGoalDefinitions = MyAppAppContext.MyAppAppContextInstance.MyAppContext.intervGoalDefinitions.Where(
    idd => idd.DLD_GoalDFID == currentGoalDefinition.DLD_GoalDFID).OrderBy(idd => idd.IDD_VolgNummer);
intervDefinitionCollection = new ObservableCollection<intervDefinition>(MyAppAppContext.MyAppAppContextInstance.MyAppContext.intervDefinitions.Where(i => i.IND_Categorie == intCategorie));
// filter intervGoalDefinitions by intervDefinitions
var intervDefinitionCollectionTemp = new ObservableCollection<intervDefinition>();
foreach (var currentintervGoalDefinity in currentintervGoalDefinitions)
{
    var foundintervGoalDefinitySorted = intervDefinitionCollection.FirstOrDefault(
        i => i.IND_intervDFID == currentintervGoalDefinity.IND_intervDFID);
    if (foundintervGoalDefinitySorted != null)
    intervDefinitionCollectionTemp.Add(foundintervGoalDefinitySorted);
}
intervDefinitionCollection = intervDefinitionCollectionTemp;

将 SQL 转换为具有两个表的 LINQ

假设NHibernate是ORM并且int_goal是目标的子类

var results = from idd in session.Query<IntGoals>()
              where idd.DlDNumber = 123456 && idd.Category.Id == 2
              orderby idd.FollowNumber
              select new { idd.Description, idd.Number };
context.int_goals_df.Join(context.goals_df, x => x.ind_number, x => x.number,
    (x, y) => new
    {
        idd = x,
        ind = y
    })
    .Where(x => x.idd.dld_number = 123456 && x.ind.categorie = 2)
    .OrderBy(x => x.idd.follownumber)
    .Select(x => new
    {
        x.ind.desc,
        x.ind.number
    });

快速开始 - 认为你需要加入

var results = from idd in session.Query<int_goals_df>()
          join ind in session.Query<goals_df>()
          on   idd.ind_number equals ind.ind_number
          where idd.DlDNumber = 123456 && idd.Category.Id == 2
          orderby idd.FollowNumber
          select new { idd.Description, idd.Number };

我倾向于使用没有隐式连接的sql语法

/*Fields*/
    SELECT ind.desc, ind.number
/*Tables*/
    FROM int_goals_df idd
    INNER JOIN goals_df ind
    ON ind.number = idd.ind_number
/*Conditions*/
    WHERE idd.dld_number = 123456
    AND ind.categorie = 2
/*Order/Grouping*/
    ORDER BY follownumber

从 Chris 的回答中可以看出,这更容易转换为 linq。