MattCucco MattCucco - 2 years ago 94 Question

Making sense of Entity Framework and IEnumerable

I am not in a position were I will be able to debug anytime soon, so I was wondering if the following code makes sense. Not familiar with

but I am just a student and my boss told me to use them.

Thanks for any help, really appreciate it! (VB.NET) (also before object is just meant to store a copy of it so I can use in my undo button)

'Get from entity framework
Dim IdNow As Integer = PartInfoNow.IdPartInfo
Dim NowPartInfo As IEnumerable(Of PartInfo) = (From a In Db.PartInfo Where a.IdPartInfo = IdNow).ToList

Dim StackUpNow As New ClsStackUp(SqlConnectionString, (New Settings1).ProgramAdmins)

Dim Before As IEnumerable(Of PartInfo) = {NowPartInfo(0)}

Answer Source

The code makes sense.

IEnumerable is a very common interface with a single method "GetEnumerator()". Anything that is an IEnumerable can be iterated through in a foreach loop. You don't really gain any advantage here (unless you want to remove other functionality that you get from the List class).

Lets assume you have this method;

Private Sub SomeMethod(ByVal integers As List(Of Integer))

    For Each i As Integer In integers
        'do something with i

End Sub

This method will only work if you pass it a list(Of Integer) or a class that derives from list(Of Integer). If you wanted to pass it an array of integers you couldn't because the types don't match. But if you change the method to this;

Private Sub SomeMethod(ByVal integers As IEnumerable(Of Integer))

    For Each i As Integer In integers
        'do something with i

End Sub

You could pass this method all kinds of collections of integers (e.g. an array instead of a list) and it would be able to handle it (so long as each collection type implemented the IEnumerable interface, which most do)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download