简体   繁体   English

Linq Group By或与Join不同

[英]Linq Group By or Distinct with Join

I may be going about this incorrectly, but I have a bookings table and a contacts table with a jointable connecting the two. 我可能不正确地处理此问题,但是我有一个预订表和一个联系表,它们之间有可连接的连接。

I need to get all bookings that have a related contact with an email containing a given string. 我需要获取所有包含具有给定字符串的电子邮件的相关联系人的预订。

In other words, users want to search bookings by contact email. 换句话说,用户希望通过联系电子邮件搜索预订。

this is what I've come up with. 这就是我想出的。 It works, but returns duplicate rows for each booking. 它有效,但是每次预订都返回重复的行。 I haven't been able to figure out how to group the rows or use a distinct method as in T-SQL... 我无法弄清楚如何对行进行分组或像在T-SQL中那样使用不同的方法...

if (!String.IsNullOrWhiteSpace(form["contactemail"]))
{
    string contactemail = form["contactemail"];
    IList<int> bookingids = bookings.Select(x => x.bookingid).ToList();
    IQueryable<contact> con = (from y in db.bookingscontacts where bookingids.Contains(y.bookingid) select y.contact);
    //EDIT:        I hadn't included the email filter...
    IQueryable<contact> conmatches = (from c in con where c.email1.Contains(contactemail) select c);
    IList<int> contactids = conmatches.Select(x => x.contactsid).ToList();

    bookings = (from r in bookings from c in db.bookingscontacts where contactids.Contains(c.contactsid) && bookingids.Contains(r.bookingid) select r);
}

Let me assume that you have navigation properties, or otherwise you will start using them: 让我假设您具有导航属性,否则将开始使用它们:

var bookings = from b in bookings
               where b.bookingscontacts
                      .Any(bc => bc.contact.email == contactemail)
               select b;

This will generate an EXISTS query, so the bookings are not duplicated. 这将生成一个EXISTS查询,因此不会重复预订。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM