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!
The most common way to compare objects in C# is to use the == operator. For predefined value types, the equality operator (==) returns true if the values of its operands are equal, false otherwise. For reference types other than string, == returns true if its two operands refer to the same object.
Note that for a single row, EF Core is slower than EF6 unless using context pooling; this could be the cost of setting up all the scoped services for each instance (which isn't done when context pooling is on). For multiple rows, EF Core batches and EF6 doesn't, so EF Core quickly becomes much faster.
Object comparison refers to the ability of an object to determine whether it is essentially the same as another object. You evaluate whether one object is equal to another by sending one of the objects an isEqual: message and passing in the other object.
Dapper vs Entity Framework CoreDapper is literally much faster than Entity Framework Core considering the fact that there are no bells and whistles in Dapper. It is a straight forward Micro ORM that has minimal features as well.
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:
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();
}
I think you can do this using LinqKit's PredicateBuilder and reflection. Alternatively, you could use reflection to generate a chain of Where
Expressions
to do the same thing.
I don't have time to put together an example, but I'm pretty sure you can do it this way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With