代码之家  ›  专栏  ›  技术社区  ›  Aeseir

比较Guid时出现异常

  •  1
  • Aeseir  · 技术社区  · 8 年前

    我正在尝试获取包含具有特定ID的站点的所有类别的列表。下面是我稍微修改过的脚手架生成方法。

            [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);
            }
    

    不幸的是,当我运行此程序时,它会引发以下错误:

    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)'
    

    实体非常简单:

        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; }
        }
    

    我会做错什么?

    1 回复  |  直到 8 年前
        1
  •  3
  •   CodeFuller    8 年前

    看起来EF Core中有个bug,检查一下 issue 在github上。替换的解决方法 Equals() 具有 == 操作员为我做得很好:

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