views:

323

answers:

2

I'm only dealing with one database table / entity object: NodePath.

Given a particular Node, I want to get only a subset of all its NodePaths according to this query:

select
    *
from
    NodePath
where
    NodeId = @GivenNodeId and
    Id in
    (
        --active paths
        select
            a.Id
        from
            NodePath a join
        (
                select
                    [Path],
                    max(Created) as Created
                from
                    NodePath
                group by
                    [Path]
        ) b on
        a.[Path] = b.[Path] and
        a.Created = b.Created
    )

How can I execute this in my VB.NET application?

Dim AllPaths = GivenNode.NodePaths.OrderByDescending(Function(p) p.Created)

Dim ActivePaths = ???
+2  A: 
I've updated this answer with more steps. Thank you, Marcel.
Zack Peterson
+3  A: 

I believe I've translated that SQL correctly, but I can make changes if necessary. This is selecting one NodePath for each common Path (based on the greatest Created), so long as it matches the NodeId.

C# Solution:

var nodePaths = (from p in context.NodePaths
                 group p by p.Path into g
                 select g.OrderByDescending(i => i.Created).First()
                 ).Where(p => p.NodeId == givenNodeId);

VB.NET Solution (I think, not my primary language):

Dim nodePaths = (From p In context.NodePaths _
                 Group p By p.Path Into Group _
                 Select Group.OrderByDescending(Function(i) i.Created).First() _
                 ).Where(Function(p) p.NodeId = givenNodeId)
Ryan Versaw
This is a little odd though, as it grabs the NodePath with the greatest Created first, then filters. This appears to be how the SQL query works though, which is why I wrote it like this.
Ryan Versaw
Also, I wrote this with LinqToSql in mind, but I'm not seeing anything that would cause issues in the Entity Framework.
Ryan Versaw
Thank you, Ryan. I've decided to go with Marcel's stored procedure suggestion for now. I know I must eventually force myself to get far more comfortable with LINQ.
Zack Peterson
Sure! Even if you don't feel comfortable having queries like this in your code, it might be interesting to run it (either normally, or with LinqPad) just to see what query it generates compared to your current one.
Ryan Versaw