Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
481 views
in Technique[技术] by (71.8m points)

c# - Linq Query where related entity contains value from array

I have a Model called JobReport which looks like this (simplified)

public class JobReport
{
    public JobReport()   
    {
        WorkOrders = new List<WorkOrder>();
    }
    public int JobID { get; set; }
    public List<WorkOrder> WorkOrders{ get; set; }
}

public class WorkOrder
{
    public WorkOrder()   
    {
        Total = 0;
    }
    public string Trade { get; set; }
    public int WorkOrderID { get; set; }
    public decimal? Total { get; set; }
}

I'd like to run a Linq query which gets me all the Jobs that have WorkOrders that have a trade which is in a passed array.

var trades = new string[] { }

I've tried something like the following which doesn't work, as it tries to get me a list of workorders, when I actually need the underlying jobs.

The problem appears to be because I'm calling Select

var jobsDB = db.Jobs.Include(x=>x.WorkOrders).ToList();

var jobs = (from p in jobsDB
                    select new JobReport()
     {
        JobID = p.JobID,
        WorkOrders = p.WorkOrders.ToList()
     }


jobs = jobs
    .Select(x => x.WorkOrders
    .Where(y => trades.Contains(y.Trade)));
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This will work:

jobs = jobs
    .Where(x => x.WorkOrders.Any(y => trades.Contains(y.Trade)));

The way I usually tackle these problems is that I look at what the outcome must be (a list of jobs) - that means we need to put the Where first, and we must look for a condition for a job to be included. It's a bit like constructing a SQL query - in fact you can use the SQL like query syntax for most LINQ tasks, if you prefer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...