【问题标题】:How to make a right join using LINQ to SQL & C#?如何使用 LINQ to SQL & C# 进行正确连接?
【发布时间】:2012-04-12 11:09:45
【问题描述】:

我在使用 LINQ 和 C# 创建以下 SQL 语句时遇到问题

    select c.IDAddenda, c.Descripcion
      from CatAddendas c 
right join EmpresaAddenda e on e.IDAddenda = c.IDAddenda
     where e.rfc = 'SUL010720JN8'
  order by c.IDAddenda asc

我知道了:

public IEnumerable<CatAddenda> TraeAddendas(string rfc)
{
    DataClasses1DataContext dc = new DataClasses1DataContext(...);

    return (from adds in dc.EmpresaAddendas
            cats.IDAddenda    into joined 
            where adds.RFC == rfc
            select adds.CatAddenda);
}

这不是正确的连接,有什么想法吗?

【问题讨论】:

标签: c# sql linq


【解决方案1】:
 var RightJoin = from adds in dc.EmpresaAddendas
                 join cats in CatAddendas 
                     on adds.IDAddenda equals cats.IDAddenda into joined
                 from cats in joined.DefaultIfEmpty()
                 select new
                 {
                     Id = cats.IDAddenda,
                     Description = cats.Descripcion 
                 };

【讨论】:

  • 这是左外连接
  • 你确定吗?
【解决方案2】:
var results = from e in EmpresaAddenda
              join c in CatAddendas
              on e.IDAddenda equals c.IDAddenda into f
              from c in f.DefaultIfEmpty()
              select new
              {
                   ID = c.IDAddenda,
                   Description = c.Descripcion 
              };

您可以根据结果应用 where 和 order by。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-14
    • 1970-01-01
    • 1970-01-01
    • 2017-11-16
    相关资源
    最近更新 更多