Michel Andrade
Michel Andrade

Reputation: 4196

Entity Framework Core Throwing Exception: The LINQ expression could not be translated with PostgreSQL

I'm trying to filter a query in ASP.NET Core 3.1, using Entity Framework Core 3.1.8 with the entities bellow:

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();

Entity Map:

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

This is the exception:

The LINQ expression 'DbSet .Where(p => p.ProductVariantProperties .Any(x => x.ProductAttributeId == 12))' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync().

It only works when using productVariantRepository.AsEnumerable(), but this returns all object from the table.

The main go is to use Json property with jsonb, but only the query filter is not working

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

Upvotes: 0

Views: 974

Answers (2)

T&#226;n
T&#226;n

Reputation: 1

The LINQ expression 'DbSet .Where(p => p.ProductVariantProperties .Any(x => x.ProductAttributeId == 12))' could not be translated.

This error occurs because the table ProductVariant doesn't have column name ProductVariantProperties. You can try to open database to check again.

That's why your linq cannot be translated to SQL statement. Something like: There is no column name ProductVariantProperties in the table ProductVariant.

I suggest to filter ProductVariantProperty that including ProductAttributeId property. Then, assigning the value to ProductVariantProperties property.

Upvotes: 2

Serge
Serge

Reputation: 43931

ProductVariantProperty doesn't have any field that can be used to connect this two tables. Add ProductVariantId to ProductVariantProperty and join this two tables them. After this you can select by ProductAttributeId.

Upvotes: 0

Related Questions