按多对多关系分组

时间:2013-11-22 11:42:18

标签: c# linq entity-framework

我有两个实体:

public class Category
{
    // Primary properties
    public int Id { get; set; }
    public string Name { get; set; }

    // Navigation properties
    public virtual ICollection<Address> Addresses { get; set; }
}

public class Address
{
    // Primary properties
    public int Id { get; set; }
    public string Name { get; set; }

    // Navigation properties
    public virtual ICollection<Category> Categories { get; set; }
}

根据一组地址ID,我需要按类别分组所有地址,包括每个地址的地址计数。

示例:

Category: {1,"WORKSHOP",{1,2}},{2,"DEALER",{1,3}}

Address:  {1,"Paul Workshop and Dealer",{1,2}}
          {2,"Joe Workshop",{1}} 
          {3,"Peter Dealer",{2}} 

如果我有地址ID 1和3,我想得到:

Categories - "WORKSHOP -  Count: 1"
             "DEALER   -  Count: 2"

如果我有地址ID 1和2,我想得到:类别 -

Categories - "WORKSHOP -  Count: 2"
             "DEALER   -  Count: 1" 

到目前为止,我得到了这个,但是这个小组没有工作:

var groupedAddresses = from add in addressQuery
                       where addressIds.Contains(add.Id)
                       group add by new { Category_Id = add.Categories, Address_Id = add.Id };

var result = from add in groupedAddresses 
             group add by add.Id into final
             join c in categoryQuery on final.Key equals c.Id
             select new CategoryGetAllBySearchDto
             {
                   Id = final.Key,
                   Name = c.Name,
                   SearchCount = final.Count()
              };

有什么想法吗?

感谢。

1 个答案:

答案 0 :(得分:2)

int[] addressIds = { 1, 3 };

var query = from c in categoryQuery
            let searchCount = c.Addresses.Count(a => addressIds.Contains(a.Id))
            where searchCount > 0
            select new CategoryGetAllBySearchDto{
               Id = c.Id,
               Name = c.Name,
               SearchCount = searchCount
            };