Only primitive types or enumeration types are supported in this context

前端 未结 3 1744
灰色年华
灰色年华 2020-11-27 07:49

I\'ve seen lots of questions on this topic, but I haven\'t been able to sort through any of them that actually solve the issue I\'m seeing. I have an activities entity that

3条回答
  •  悲哀的现实
    2020-11-27 08:48

    The problem with using == and obj.Equals is that Entity Framework doesn't know how to translate that method call into SQL---even if you overload those two methods into something that would translate into SQL. What you can do to fix this shortcoming in Entity Framework is to create a method that returns an Expression Tree that does the more complex equality checking you are wanting to do.

    For example, let's say we have the following class

    public class Person {
        public string Firstname { get; set; } 
        public string Lastname  { get; set; }
    }
    

    In order to return a custom equality operation that Entity Framework can understand, add the following method to the Person class:

    public static Expression> EqualsExpressionTree(  Person rhs )
    {
        return ( lhs ) => string.Equals( lhs.Firstname, rhs.Firstname ) &&
                          string.Equals( lhs.Lastname, rhs.Lastname );
    }
    

    In your LINQ queries, you can leverage your custom equality code like so:

    Person anotherPerson = new Person { Firstname = "John", Lastname = "Doe" }
    personCont.Where( Person.EqualsExpressionTree(anotherPerson) );
    //...
    if ( personCont.Any( Person.EqualsExpressionTree(anotherPerson)) ) {
    //...
    

    Furthermore, the EqualsExpressionTree method can be rewritten to call a static Equals method, allowing you to leverage your custom equality logic. However, in all things, remember that your code must translate to a SQL expression, since we are, after all, calling to a database and not accessing stuff from memory.

提交回复
热议问题