.net – How to extend ADO.NET Entity Framework objects with partial classes

entity-frameworklinqlinq-to-entitiesnetvb.net

I've created a Visual Basic WPF Application project that contains Toy.edmx, an ADO.NET Entity Data Model generated from a database called Toy.

Its Window1.xaml.vb file looks like this:

1   Class Window1
2   
3       Private Sub Window1_Loaded( _
4       ByVal sender As System.Object, _
5       ByVal e As System.Windows.RoutedEventArgs) _
6       Handles MyBase.Loaded
7   
8           Dim dc As New ToyEntities1
9           Label1.Content = (From c As Client In dc.ClientSet _
10                            Select c).First.FirstName
11  
12      End Sub
13  
14  End Class

That runs just fine.

But, if I add the file Client.vb

1   Partial Public Class Client
2       Function IsWashington() As Boolean
3           Return Me.LastName = "Washington"
4       End Function
5   End Class

…and add a WHERE clause to my Window1.xaml.vb query…

9           Label1.Content = (From c As Client In dc.ClientSet _
10                            Where c.IsWashington _
11                            Select c).First.FirstName

…then I get this NotSupportedException:

LINQ to Entities does not recognize the method 'Boolean IsWashington()' method, and this method cannot be translated into a store expression.

How do I extend ADO.NET Entity Framework objects with partial classes?

Best Answer

Is this what you're trying to do - create a method that applies a filter to Client queries.

I don't know vb.net, so don't trust this free-hand code 100%.

Partial Public Class Client
  Public Shared Function IsWashington(query As IQueryable(Of Client)) As IQueryable(Of Client)
    Return query.Where(Function(someClient) someClient.LastName = "Washington")
  End Function
End Class

later, some calling code.

IQueryable(Of Client) someQuery = dc.ClientSet.AsQueryable
someQuery = Client.IsWashington(someQuery)

Label1.Content = someQuery.First.FirstName

Hope this works!