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

时间:2021-03-03 09:35:51

标签: c# entity-framework entity-framework-core ef-core-3.1

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

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.

如何在不需要将主键更改为原始类型的情况下从数据库接收数据?

1 个答案:

答案 0 :(得分:1)

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

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