EF VB多对多LINQ问题和疑虑

时间:2015-02-22 19:53:25

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

在以下2个问题上寻求帮助(因为无法在线找到直接或类似的解决方案)。

该集......

Partial Public Class Profile
    Public Property Id As Long
    Public Property ProfileTitle As String

    Public Overridable Property Categories As ICollection(Of Category) = New HashSet(Of Category)
End Class

Partial Public Class Category
    Public Property Id As Long
    Public Property ParentId As Long
    Public Property Name As String

    Public Overridable Property ChildrenCategories As ICollection(Of Category) = New HashSet(Of Category)
    Public Overridable Property PrentCategory As Category
    Public Overridable Property Profiles As ICollection(Of Profile) = New HashSet(Of Profile)
End Class

提示是列出所有不同的类别,每个类别中的配置文件数量(受配置文件限制)。

与以下SQL类似:

SELECT c.Id,c.Name,Count(p.Id) Cnt
FROM Categories c
    JOIN ProfilesInCategories pic ON pic.CategoryId = c.Id
    JOIN Profiles p On p.Id = pic.ProfileId
WHERE p.ProfileTitle like ('%frost%')
GROUP BY c.Id,c.Name
ORDER BY c.Name ASC

问题是:

  1. 我是EF和LINQ的新手。无法弄清楚类别的LINQ语句

    (来自c在AppModel.Categories.Include(“个人档案”中)                             来自p In c.Profiles                             p.ProfileTitle.Contains(“霜”)                         选择New With {.Id = c.Id,.Name = c.Name,.Count = c.Profiles.Count})。Distinct()

  2. 尽管上述语句返回了正确的配置文件的正确类别,但它并未正确返回计数(返回的计数适用于返回类别中的所有配置文件)。

    1. 这是最有效的方法吗?考虑到Profiles将受到其他标准的进一步限制,是否有更好的技术?
    2. 非常感谢所有帮助。

      由于


      我能够让LINQ返回正确的结果,但仍然想知道这是否是最佳解决方案......

      From c In Categories.Include("Profiles") _
              From p In c.Profiles _
              Where p.ProfileTitle.Contains("frost") _
              Group c By c.Id, c.Name Into Group _
              Select New With {.Id = Id, .Name = Name, .Count = Group.Count()}
      

      From p In Profiles.Include("Categories") _
              Where p.ProfileTitle.Contains("frost") _ 
              From c in p.Categories _
              Group c By c.Id, c.Name Into Group _
              Select New With {.Id = Id, .Name = Name, .cnt = Group.Count}
      

0 个答案:

没有答案