簡體   English   中英

有查詢想要它在LINQ(內部聯接)中

[英]Have a Query want it in LINQ(Inner Join)

我在使用C#將查詢轉換為LINQ時遇到問題,這是我的查詢

select PDF.Name,PDF.Name
from PDF inner join PC
on PDF.Id=PC.Ref_PDF
having pc.Ref_Customer=_id

您應該知道_id是我發送給我的方法的東西,所以我可以用它找到一些東西

到目前為止,我做了我認為不可行的操作(導致出現很多錯誤)

無效的表達方式“選擇”

預期的上下文關鍵字“等於”

兩者都在這里結尾, join p in Context.PDFs on c.Ref_PDF

     internal List<EF_Model.PDF> Customers_File(int _id)
           {
               using (var Context = new EF_Model.CoolerEntities())
                  {
                    var q = from c in Context.PCs
                            where c.Ref_Customer == _id
                            join p in Context.PDFs on c.Ref_PDF
                            select new { c.PDF.Id, c.PDF.Name, c.PDF.File };
                    return q;
                  }
           }

我們如何使其成為linq語句?

這應該為您完成工作

from pc in context.PCs where pc.Ref_Customer == _id
join p in context.PDFs on pc.Ref_PDF equals p.Ref_PDF
select new {pc.PDF.Id, pc.PDF.Name, pc.PDF.File }

可能是您說錯了,我假設您看到了句法錯誤

修復查詢的語法

List<EF_Model.PDF> Customers_File(int _id) {
    using (var Context = new EF_Model.CoolerEntities()) {
        var q = from c in Context.PCs
                join p in Context.PDFs on c.Ref_PDF equals p.Id
                where c.Ref_Customer == _id
                select new EF_Model.PDF { Id = c.PDF.Id, Name = c.PDF.Name, File = c.PDF.File };
        return q.ToList();
    }
}

並且該方法希望返回列表,因此從該方法返回時在查詢上使用ToList()

更新:

如果只是要返回PDF模型,則無需創建匿名對象,只需返回c.PDF

List<EF_Model.PDF> Customers_File(int _id) {
    using (var Context = new EF_Model.CoolerEntities()) {
        var q = from c in Context.PCs
                join p in Context.PDFs on c.Ref_PDF equals p.Id
                where c.Ref_Customer == _id
                select c.PDF;
        return q.ToList();
    }
}

如果設置導航屬性,則查詢為:

var q =
  from pc in Context.PCs
  where pc.Ref_Customer == _id
  from pdf in pc.PDFs
  select pdf;

如果您不這樣做:

var q =
  from pc in Context.PCs
  where pc.Ref_Customer == _id
  join pdf in Context.PDFs on pc.Ref_PDF equals pdf.Id
  select pdf;

關於連接語法的主要知識,它具有以下形式

“加入的(a)(b)(c)上等於(d)”

  • (a):( b)成員的新范圍變量
  • (b):您要加入的項目的來源-合並的右側。
  • (c):一個表達式,其中聯接左側的項在范圍內。
  • (d):表達式,其中聯接右側的項在范圍- (a)中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM