联接几个表而不重复相同的数据

时间:2019-01-14 19:08:40

标签: c# .net linq lambda

我有两个桌子, 反馈表和步骤表。每个反馈都有多个步骤。如果我将LINQ与join方法一起使用,它将在FeedbackViewModel中返回相同数量的步骤项(obj),并且每个步骤项仅包含1个单个步骤。我的意思是类似于SQL返回。

FeedbackViewModel[0]{FeedbackID = 1,FeedbackName="NameA", Steps{Step1}}
FeedbackViewModel[1]{FeedbackID = 1,FeedbackName="NameA", Steps{Step2}}
FeedbackViewModel[2]{FeedbackID = 1,FeedbackName="NameA", Steps{Step3}}

但是我只想要一个包含许多步骤的FeedbackViewModel对象。

FeedbackViewModel[0]{FeedbackID = 1,FeedbackName="NameA", Steps{Step1, Step2, Step 3 etc..}

我可以通过foreach循环来做到这一点,但是看起来并不专业。

感谢帮助

public class Feedback 
{
    public int FeedbackID { get; set; }
    public string FeedbackName { get; set; }        
}

public class StepModel
{
    public int StepID { get; set; }
    public int FeedbackID { get; set; } = 0;
    public int StepNumber { get; set; }
    public string StepDetail { get; set; }
    public virtual Feedback FeedBack { get; set; }
}

public class FeedbackViewMODEL
{
    public int FeedbackID { get; set; }
    public string FeedbackName { get; set; }
    public List<StepModel> Steps { get; set; }
}


var quote = from feed in FeedBacks 
           join stp in StePs on feed.FeedbackID equals stp.FeedbackID
           where feed.FeedbackID == id
           select new FeedbackViewMODEL
                    {
                        Step = stp;
                    }

2 个答案:

答案 0 :(得分:0)

我认为您应该离开外部联接。

来自反馈中的提要         将stp在feed.FeedbackID上等于stp.FeedbackID的步骤中加入结果         其中feed.FeedBackID == id和result.DefaultIfEmpty()

答案 1 :(得分:0)

使用LINQ组联接将合并所有匹配的步骤:

var quote = from feed in FeedBacks
            where feed.FeedbackID == id
            join stp in StePs on feed.FeedbackID equals stp.FeedbackID into stpj
            select new FeedbackViewMODEL {
                FeedbackID = feed.FeedbackID,
                FeedbackName = feed.FeedbackName,
                Steps = stpj.ToList()
            };