开发者

Complex LINQ query in a workflow

We开发者_开发技巧 have a "Documents" table. Each document must be approved before it turns active.

Document approval process requires multiple participants. For example, designer approves first, executive manager second, general manager third. General manager can't approve before executive.

The Document has a collection of Approvers. "Approvers" have "Index", "ApproverName" and "Approved" properties.

The question is how use LINQ to show the list of documents the user has to approve now. Documents should appear in the list when it's time for specific user to approve them.

So far we've been using the following manual filtering code:

   Public ReadOnly Property RequiresMyApproval() As Boolean

        Get


            If Me.Approved OrElse Me.Approvals.Count = 0 Then Return False

            Dim closestUnapproval = GetClosestUnapproval()

            Return (closestUnapproval IsNot Nothing AndAlso closestUnapproval.ParentUser.Oid = CurrentUser.Oid)

        End Get

    End Property


    Private Function GetClosestUnapproval() As DocumentApproval
        Dim closestUnapprovedIndex As Integer = -1
        Dim closestUnapproval As DocumentApproval = Nothing



        For Each approval In Me.Approvals
            If Not approval.Approved AndAlso approval.Index < closestUnapprovedIndex OrElse Not approval.Approved AndAlso closestUnapprovedIndex = -1 Then
                closestUnapprovedIndex = approval.Index
                closestUnapproval = approval
            End If
        Next


        Return closestUnapproval

    End Function


I recommend you to use LinqKit (http://www.albahari.com/nutshell/linqkit.aspx) free library, it helps with dynamic queries in LINQ... You can also use LinqPad to test you queries easy without need to code anything first...


If I understand the problem correctly:

//The person who we're building this query around
Approver me;

Documents
    .Where(d => !d.Approvers.Where(a => a == me).First().Approved)
    .Where(d => 
        d.SelectMany(x =>
            x.Approvers
            .Where(a => a.Index < me.Index)
            .Where(a => !a.Approved))
    .Count() == 0)

What this does is for each document, it finds you in the list of approvers and checks that you haven't approved this document yet. If you have not, then it selects all the approvers less than you, and gets the count of them who have not yet approved this document, if that count is zero then the document passes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜