使用LINQ .Join()方法

时间:2012-06-27 14:33:04

标签: asp.net-mvc-3 linq entity-framework

我想在LINQ中使用.Join()方法来执行以下SQL:

select * from Enquiries e, QuoteLines q where e.EnquiryId = q.EnquiryId and e.AccountNum = '123' and q.LineNumber = 'ABC123'

AccountNumLineNumber使用的参数将动态传递给方法。

如何将其传输以使用LINQ .Join()方法?

public ActionResult EnquirySearch(string id)
{
    var enquiries = new List<Enquiries>();    

    if(id.Contains(' '))
    {
        string[] searchArr = id.Split(' ');
        // want to do my LINQ here
        // this will be split so the first element in the array is the AccountNum
        // and the second element in the array is the LineNumber
    }
    else
    {
        enquiries = context.Enquiries.Where(x=>x.QuoteRef.Contains(id) 
        || x.AccountNum.Contains(id) || x.Owner.Contains(id));
    }
    return View(enquiries);
}

2 个答案:

答案 0 :(得分:2)

在表达式查询中表达连接更容易,它可以是:

var query = from e in Enquiries
            join q in QuoteLines on e.EnquiryId equals q.EnquiryId
            where e.AccountNum == accountNum && q.LineNumber == lineNumber
            select new { Enquiry = e, QuoteLine = q };

或者你可以过早地过滤 - 这会对LINQ to Objects产生影响,但几乎肯定不会在LINQ to SQL / EF中出现:

var query = from e in Enquiries
            where e.AccountNum == accountNum
            join q in QuoteLines.Where(qq => qq.LineNumber == lineNumber)
              on e.EnquiryId equals q.EnquiryId
            select new { Enquiry = e, QuoteLine = q };

答案 1 :(得分:1)

使用Join()

var query = context.Enquiries.Where(e=>e.AccountNum == accountNum)
.Join(context.QuoteLines.Where(q=>q.LineNumber==lineNumber),
 e => e.EnquiryID, q => q.EnquiryID,(e,q)=>e);

这看起来比较棘手,但确实有智能感知支持。 我不知道第四个论点是如何运作的,但确实如此。