簡體   English   中英

LINQ內部聯接4個表(將SQL轉換為C#LINQ)

[英]LINQ inner join 4 tables (convert SQL to C# LINQ)

你好。 我正在嘗試加入4個桌子:

tStore(StoreID,Store_Name)

tSection(SectionID,Section_Name)

tSectionSqft(SectionSqftID,StoreID,SectionID,Sqft)

tSectionForwardSelling(SectionForwardSellingID,StoreID,SectionID,金額,日期)

我希望查詢給我結果:

商店名稱,科目名稱,平方英尺,金額

我需要將此SQL查詢轉換為C#LINQ:

SELECT
    tStore.Store_Name, 
    tSection.Section_Name,  
    tSectionSqft.Sqft,  
    tSectionForwardSelling.Amount
FROM tSection  
INNER JOIN tSectionForwardSelling 
      ON tSection.SectionID = tSectionForwardSelling.SectionID 
INNER JOIN tSectionSqft 
      ON tSection.SectionID = tSectionSqft.SectionID 
INNER JOIN tStore 
      ON tSectionForwardSelling.StoreID = tStore.StoreID 
         AND tSectionSqft.StoreID = tStore.StoreID

我自己嘗試,但是每次LINQ給我錯誤的結果。

var queryResult = from a in tSection
            join b in tSectionForwardSelling on a.SectionID equals b.SectionID 
            join c in tSectionSqft on a.SectionID equals c.SectionID
            join d in tStore on new { u1 = b.SectionID , u2 = c.SectionID } equals new { u1 = d.SectionID , u2 = d.SectionID }
            select new { d.Store_Name, a.Section_Name, c.Sqft, b.Amount };

您應該執行以下操作(只是一個片段):

var result = from s in tSection join  ss in tSectionForwardSelling on s.SectionId equals ss.sectionID
        join sq in tSectionSqft on s.SectonId equals sq.SectionID
        join st in stores on ......
        select new {field1 = s.Field1
                    field2 = sq.FieldName,...}

嘗試這個:

public class RetrieveData
{
    public string StoreName { get; set; }
    public string SectionName { get; set; }
    public int Sqft { get; set; }
    public int Amount { get; set; }
}

public void Method(tStore store)
{
    // Store_Name, Section_Name, Sqft, Amount

    var list = from se in Context.Sections
               join fs in tSectionForwardSelling on se.SectionID equals fs.SectionID 
               join sqft in tSectionSqft on se.SectionID equals sqft.SectionID
               join st in tStore on new { u1 = fs.StoreID , u2 = st.StoreID } equals new { u1 = sqft.StoreID , u2 = st.StoreID }
               select new RetrieveData() {
                   StoreName = st.Store_Name,
                   SectionName = se.Section_Name,
                   Sqft = sqft.Sqft,
                   Amount = fs.Amount };
}

我想部分感謝@Nazmul的join

暫無
暫無

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

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