1

I create a Menu class that has a self-relation.

Public Class Menu
    Sub New()
        Me.lstmenu = New List(Of Menu)
    End Sub
    Property MenuID As Integer
    Property Title As String
    Property Description As String
    Property URL As String
    Property lstmenu As ICollection(Of Menu)
End Class

Entity Framework code-first creates a table from this class with a self relation.

SQL table made by code first

I want to write a query with Linq to return me all menus that their foreign key are null but all I have is a lstmenu that hold a list of menus. And I can't find any FK column to use in my query.

Please help me how to write a query to find all records that their foreign key are null.

1
  • Thanks to @marc_c for edit Commented Jan 4, 2016 at 19:48

1 Answer 1

1

One thing you can do is declare the FK property in your Menu entity as nullable integer and the navigation property that represent the other end of your relationship. The following solution is using Data Annotations:

Public Class Menu
    Sub New()
        Me.lstmenu = New List(Of Menu)
    End Sub
    Property MenuID As Integer

    <ForeignKey("ParentMenu")>
    Property ParentMenuID As Integer? 'Change the FK name and nav. property name at your convinience
    Property ParentMenu As Menu

    Property Title As String
    Property Description As String
    Property URL As String
    Property lstmenu As ICollection(Of Menu)
End Class

If you want to configure your relationship using Fluent Api to avoid using attributes in your model, you can also do the same overriding OnModelCreating method of your context:

Protected Overrides Sub OnModelCreating(ByVal modelBuilder As DbModelBuilder)

    modelBuilder.Entity(Of Menu)().
    HasOptional(Function(t) t.ParentMenu).
    WithMany(Function(t) t.lstmenu).
    HasForeignKey(Function(t) t.ParentMenuId)

End Sub

Now you can verify in your queries if a menu have associated a parent menu checking if the FK property is null or not

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot @octavioccl your first solution works perfect. I do this: <code> 'Public Class Menu Sub New() Me.lstmenu = New List(Of Menu) End Sub Property MenuID As Integer <ForeignKey("lstmenu")> Property ParentMenuID As Integer? Property Title As String Property Description As String Property URL As String Property lstmenu As ICollection(Of Menu) End Class' </code> and it works well. thanks again

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.