OData / odata.github.io

Documentation source of Microsoft OData stack.
http://odata.github.io/
Other
12 stars 8 forks source link

Issue with filter by enum value #27

Open rich0726 opened 3 years ago

rich0726 commented 3 years ago

Hello! I am building an OData API on top of EntityFrameworkCore, Code-First to a SQL Server database. I'm having trouble with a specific syntax for filter queries.

For purposes of explaining the code easily, I abstracted down a simple Posts and Tags example. Posts and Tags are a many-to-many relationship. Here are my entity classes:

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace ExampleNS
{
    public enum tagEnum 
    {
        Tag1=0,
        Tag2=1,
        Tag3=2,
        Tag4=3,
        Tag5=4
    }

    public enum CategoryEnum
    {
        Social=0,
        Private=1,
        Public=2,
        Foo=3
    }

    public class Post
    {
        public Post()
        {
            Tags = new HashSet<Tag>();
        }
        public CategoryEnum Category { get; set; }
        public int PostId { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }
        public ICollection<Tag> Tags { get; set; }
    }
    public class Tag
    {
        public Tag()
        {

        }
        [Key]
        public tagEnum Tags { get; set; }
        public string TagValue { get; set; }
        public ICollection<Post> Posts { get; set; }
    }
}

I want to be able to filter Posts based on an any/all style collection filter, like this: http://localhost:5000/odata/posts?$filter=Tags/any(c: c/Tags eq ExampleNS.tagEnum'Tag1')

However, when doing that, it returns an error: "The query specified in the URI is not valid. A binary operator with incompatible types was detected. Found operand types 'ExampleNS.Tag' and 'Edm.String' for operator kind 'Equal'.",

Can't figure out why this is happening, but I assume I need to write some sort of value conversion or IComparable implementation to get it to filter correctly. Any help is greatly appreciated!