Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 321
Zack Peterson Avatar asked Nov 03 '08 22:11

Zack Peterson


3 Answers

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!

like image 125
Amy B Avatar answered Oct 12 '22 10:10

Amy B


The problem is that you're writing code, and expecting the Entity Framework to translate that into SQL... it can't do that. Just like LINQ to SQL can't do that.

Imagine if your property read a file from the "C:\" drive... how do you think it would handle that? - not possible.

like image 35
Timothy Khouri Avatar answered Oct 12 '22 10:10

Timothy Khouri


What type is Client class?

You might need to add namespace (same as that in which Client "Entity classs" is defined) to the file containing "IsWashington".

like image 26
shahkalpesh Avatar answered Oct 12 '22 12:10

shahkalpesh