实体框架核心抛出异常:LINQ表达式无法用PostgreSQL翻译

时间:2020-10-29 01:30:05

标签: c# asp.net entity-framework asp.net-core entity-framework-core

我正在尝试使用实体框架Core 3.1.8和以下实体来过滤ASP.NET Core 3.1中的查询:

public class ProductVariant
{
        public Guid DepositId { get; set; }
        public Collection<ProductVariantProperty> ProductVariantProperties { get; set; }
        public int Quantity { get; set; }
}

public class ProductVariantProperty
{
    public int ProductAttributeId { get; set; }
    public int ProductAttributeValueId { get; set; }
}

This is the query I'm using:
    
var result = productVariantRepository
                .Where(p => p.ProductVariantProperties.Any(x => x.ProductAttributeId == 12))
                .ToList();

实体图:

builder.Entity<ProductVariant>(b =>
{
     b.ToTable(CommerceConsts.DbTablePrefix + "ProductVariants", CommerceConsts.DbSchema);
     b.ConfigureByConvention();
     b.Property(x => x.ProductVariantProperties).HasColumnType("jsonb");
     b.HasOne<Deposit>().WithMany().HasForeignKey(x => x.DepositId).IsRequired();
});    
           

这是一个例外:

LINQ表达式'DbSet 哪里(p => p.ProductVariantProperties .Any(x => x.ProductAttributeId == 12))'无法翻译。可以采用以下形式重写查询: 翻译,或通过插入 调用AsEnumerable(),AsAsyncEnumerable(),ToList()或 ToListAsync()。

仅在使用 productVariantRepository.AsEnumerable()时有效,但这将返回表中的所有对象。

主要措施是将Json属性与jsonb一起使用,但仅查询过滤器不起作用

https://www.npgsql.org/efcore/mapping/json.html?tabs=data-annotations%2Cpoco

2 个答案:

答案 0 :(得分:2)

LINQ表达式'DbSet。where(p => p.ProductVariantProperties .ny(x => x.ProductAttributeId == 12))无法翻译。

发生此错误是因为表ProductVariant没有列名ProductVariantProperties。您可以尝试打开数据库以再次检查。

这就是为什么您的linq无法转换为SQL语句的原因。 ProductVariantProperties 中没有列名ProductVariant

我建议过滤包含ProductVariantProperty属性的ProductAttributeId。然后,将值分配给ProductVariantProperties属性。

答案 1 :(得分:0)

ProductVariantProperty没有可用于连接这两个表的任何字段。将ProductVariantId添加到ProductVariantProperty,并将这两个表加入其中。之后,您可以通过ProductAttributeId进行选择。