Aeseir
Aeseir

Reputation: 8414

Exception when comparing Guid

I am trying to get a list of all categories that contain a site with a specific ID. Below is the scaffold generated method i slightly modified.

        [HttpGet("Categories/{id}")]
        public async Task<IActionResult> GetCategoriesSite([FromRoute] Guid id)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            // This line throws the error
            var categories = await _context.Categories.Where(o => o.Site.Id.Equals(id)).ToListAsync();

            if (categories == null)
            {
                return NotFound();
            }

            return Ok(categories);
        }

Unfortunately when i run this it throws the following error:

System.ArgumentException: Expression of type 'System.Nullable`1[System.Guid]' cannot be used for parameter of type 'System.Guid' of method 'Boolean Equals(System.Guid)'

Entities are very simple:

    public class Category
    {
        public Guid Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }

        public Site Site { get; set; }
    }

    public class Site
    {
        public Guid Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }

        public ICollection<Category> Categories { get; set; }
    }

What could i be doing wrong?

Upvotes: 1

Views: 616

Answers (1)

CodeFuller
CodeFuller

Reputation: 31282

Seems like a bug in EF Core, check this issue on github. Workaround with replacing of Equals() with == operator worked fine for me:

var categories = await _context.Categories.Where(o => o.Site.Id == id).ToListAsync();

Upvotes: 3

Related Questions