Comparing Objectity Framework Objects

I'm having problems comparing objects in an entity Framework 4.0. After searching a lot of time, I found a blog post in 2008 that talked about my problem and why this is happening. A blog post detailing my problem .

To summarize a blog post, you cannot perform a normal mapping of objects to an EF structure. for instance

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: Cannot create a constant value of type "Foo". In this context, only primitive types (such as Int32, String, and Guid) are supported.

It is designed according to MicroSoft.

Can someone point me aside to find out if such a comparison of objects is supported if I do some kind of magical interface or magical overload? many thanks!

+6
source share
2 answers

Because EF needs to translate your LINQ statements into SQL statements, you cannot do this. If you have complex comparison logic in your overridden Equals() method, you will have to duplicate this in the LINQ statement.

Since LINQ uses deferred execution, you can probably encapsulate this logic in a method that returns an IQueryable<T> , which you can include elsewhere.

Here is an example:

 public IQueryable<Foo> FoosEqualTo(IQueryable<Foo> allFoos, Foo target) { return from foo in allFoos where foo.Id == target.Id // or other comparison logic... select foo; } public Foo getFoo(Foo target) { return FoosEqualTo(DC.foos, target).FirstOrDefault(); } 
+6
source

I think you can do it using LinqKit PredicateBuilder and reflections. Alternatively, you can use reflection to create a chain of Where Expressions to do the same.

I don’t have time to put together an example, but I’m sure you can do it this way.

0
source

Source: https://habr.com/ru/post/903404/


All Articles