基于非原始类型主键的ef核心查询

Ef core query based on non primitive type primary key

我有一个带有非原始类型主键的聚合根:

public class Category : AggregateRoot<CategoryId>
{
    // some properties
}

public class CategoryId : ValueObject<CategoryId>
{
    public Guid Identity { get; private set; }
}

还有我的实体配置:

  public class CategoryConfiguration : IEntityTypeConfiguration<Category>
    {
        public void Configure(EntityTypeBuilder<Category> builder)
        {
            builder.HasKey(x => x.Id);
            builder.Property(x => x.Id)
                .HasConversion(
                    v => v.Identity,
                    v => new CategoryId(v));

            builder.ToTable("Categories");
        }
  }

我在插入新数据时没有问题,但是当我想使用以下代码从数据库接收数据时,我收到了来自 Ef core 3.1.4 的错误:

var categories = _context.Categories.FirstOrDefault(category=> category.Id.Identity == "someId");

Error :  failed The LINQ expression 'DbSet<Category>
          .Where(t => t.Id.Identity == __categoryId_0)' could not be translated.

如何在不将主键更改为基本类型的情况下从数据库接收数据?

我最终通过将聚合 ID 与 FirstOrDefault 中的新值对象进行比较解决了问题:

 var category = _context.Categories.FirstOrDefault(c=> c.Id == new CategoryId("someId"));