1

自从我试图提出一种优化的查询方式以来,这一直困扰着我一段时间。

因此,假设我有 3 个交叉引用表,它们共享一个公共列,该公共列将在包含更多信息的主表上进行最终连接。

例如:

假设我有以下内容:

 Customers //properties: ID, Name, Address
 IEnumberable<CustomerSports> //properties: CustomerID, SportsID
 IEnumberable<CustomerLocation> //properties: CustomerID, LocationID
 IEnumberable<CustomerPets> //properties: CustomerID, PetsID

所以我可以进行如下查询:

给我一份住在纽约 (CustomerLocation) 的打曲棍球、足球、足球 (CustomerSports)... 并养狗和猫 (CustomerPets) 的客户列表。查找表可以为空,因此客户可以进行运动,但没有宠物。

然后,当我获得客户列表时,我将加入客户表中的公共列 (CustomerID) 以检索 ID、名称和地址。

我正在考虑让客户表在每次查找时加入,然后进行联合以获取客户列表,但我不知道这是否是正确的做法。

4

2 回答 2

5

只要您正确设置了设计,那么每个人都Customer应该有一个Sports集合、一个Pets集合和一个Locations(除非最后一个是一对一的连接?)。

如果设置了这些关系,那么您可以查询如下:

var sports = new string[] { "lacrosse", "football", "soccer" };
var pets = new string[] { "cat", "dog" };
var locations = new string[] { "new york" };
var sportyPetLoversInNewYors = db.Customers
    .Where(cust => sports.All(sport => cust.Sports.Any(custSport => custSport.Name == sport)))
    .Where(cust => pets.All(pet => cust.Pets.Any(custPet => custPet.Name == pet)))
    .Where(cust => locations.All(loc => cust.Locations.Any(custLoc => custLoc.Name = loc)))
    // could customise the select here to include sub-lists or whatever
    .Select();

这假设您只想要满足所有 6 个条件的人。如果您希望人们至少喜欢其中一项运动,至少有其中一只宠物,并且(假设您使用了多个位置)至少在其中一个位置,则Where表达式将更改如下

.Where(cust => cust.Sports.Any(custSport => sports.Contains(custSport.Name)))

如果您需要进一步解释,请告诉我。

于 2014-02-18T00:49:26.093 回答
1

一种方法,如果我明白你在追求什么。允许多种运动和多种宠物,或者没有。

        var contacts = from cust in customer
                       join sport in sports on cust.CustomerID equals sport.CustomerID into multisport from sport in multisport.DefaultIfEmpty()
                       join loc in location on cust.CustomerID equals loc.CustomerID
                       join pet in pets on cust.CustomerID equals pet.CustomerID into multipet from pet in multipet.DefaultIfEmpty()

                       select new
                       {
                           cust.CustomerID,
                           multisport,
                           loc.LocationID,
                           multipet
                       };
于 2014-02-17T23:53:07.470 回答