c# - 基于非原始类型主键的ef核心查询
问题描述
我有一个非原始类型主键的聚合根:
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"));
推荐阅读
- ffmpeg - 如何在不使用 FFmpeg 重新编码的情况下连接 MTS 视频并应用过滤器?
- python - 如何在不创建新键的情况下访问 for 循环中的现有 dict 键?
- linux - 有没有办法将基于 dd 的文件挂载为 cstore 池的磁盘
- python - 如何在不使用“全局”的情况下更改 Python 函数中的变量
- css - 响应式柱廊,保持独立滚动
- vaadin - 带有 HTML 标签的 Vaadin 14 LoginI18n?
- c++ - 在哪里可以找到有关阅读 OutputDebugString() 消息的官方文档?
- php - laravel formrequest 在中间件之前
- python-3.x - 如何使用 python 自动化 MS Word
- azure - 就安全性和性能而言,哪种连接最适合将本地连接到 Azure PaaS 服务?