Search code examples
c#entity-frameworkequality

How to streamline memory object equality comparison in Entity Framework condition?


If I load an object through Entity Framework, and persist it to later use it - for example in an equality filter - Entity Framework throws the following error:

Unable to create a constant value of type 'MyType'. Only primitive types or enumeration types are supported in this context.

This can then easily be solved by using an identifying value/value combination on MyType, such as .Where(x => x.Name == MyTypeMemoryInstance.Name).

However, I was wondering if there is an alternative to allow the equality comparison without having to provide the primitive type so I can do .Where(x => x == MyTypeMemoryInstance) instead, and still do so in SQL rather than in memory.

Conceptually, this could be solved if I can provide the LINQ-to-SQL translation with the specific primitive type comparison to use for a given type, similar to overriding regular equality comparison in C#, but I don't know if this is actually possible. Thank you.


Solution

  • Best I can think of, because in where clause you have Func would be:

    public class MyType
    {
        public int Id { get; set; }
        public string Name { get; set; }
    
        public Func<MyType, bool> GetQuery()
        {
            // or whatever equals you would like
            return x => x.Name == this.Name && x.Id == this.Id;
        }
    }
    

    Then use it like for example:

    var first = ctx.MyTypes.First();
    var listContainingLoadedThings = ctx.MyTypes.Where(first.GetQuery()).ToList();