I am having troubles comparing objects In entity Framework 4.0. After googling for a while I found a blog post in 2008 which stated what my problem was and why it is occuring.Blog post describing my problem in depth.
To sum up the blog post you cannot do a custom object comparison with the EF framework at all. For example
public Foo
{
public int ID{get;set;}
public string Name {get;set;}
//I overrode the .Equals AND the == operator
}
public getFoo(Foo target)
{
DC.foos.FirstOrDefault(x => x == target);
}
System.NotSupportedException: Unable to create a constant value of type ‘Foo’ Only primitive types (‘such as Int32, String, and Guid’) are supported in this context.
This is by design according to MicroSoft.
Can someone point me in a direction to find if this sort of Object comparison is supported if I do some magic interface or magic overload? thank you very much!
Since EF needs to translate your LINQ statements to SQL statements, you can’t do this. If you have complex comparison logic in your overridden
Equals()method you will have to duplicate that in the LINQ statement.Since LINQ uses deferred execution you could probably encapsulate that logic in a method that returns an
IQueryable<T>you can incorporate elsewhere.Here’s an example: