I am looking for some guidance/help on how to approach my problem as I'm running out of ideas. I am trying to take a custom extension function and pass it to the database via Entity Framework (EF Core 3.1) using Linq to Entities but I am getting a "{method} could not be translated" error regardless of what I do. I have tried using HasDbFunction along with HasTranslation using this link Thinktecture - Entity Framework Core - Custom Functions (using HasDbFunction) to no avail. I have also tried to registera custom DbCommandInterceptor with this link Medium - Interception in Entity Framework Core and it never hits the breakpoint or logs any of my debug statements. I'm not sure what to try next but I'm looking for help on what I'm doing wrong or guidance on what to research next.
For some context with my problem I am using the class setup below:
namespace Rebates.Models
{
public class Rebate
{
public int Id { get; set; }
public string ProductName { get; set; }
public ActiveDateRange ActiveDateRange { get; set; }
public decimal Discount { get; set; }
}
public class ActiveDateRange
{
public int StartMonth { get; set; }
public int EndMonth { get; set; }
}
}
DbContext:
namespace Rebates.DB
{
public class RebateContext : DbContext
{
public DbSet<Rebate> Rebates { get; set; }
}
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
options.UseSqlServer("Server=(local);Database=Rebates;Trusted_Connection=True;");
}
}
Extension Method I'm trying to turn into a SQL statement:
namespace Rebates.ExtensionMethods
{
public static class Extensions
{
public static bool IsActive(this Rebate rebate, DateTime date)
{
return date.Month >= rebate.ActiveDateRange.StartMonth && date.Month <= rebate.ActiveDateRange.EndMonth;
}
}
}
Call I'm attempting to make in my program:
using (var db = new RebateContext())
{
var rebates = db.Rebates.Where(x => x.IsActive(DateTime.Now));
}
Error Received:
System.InvalidOperationException: 'The LINQ expression 'DbSet .Where(c => EF.Property(c, "ActiveDateRange").IsActive(DateTime.Now))' 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(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.'
I stripped out all of my failing code to hopefully make this cleaner but I can post my failed attempts as well if it will help, I just didn't want to clutter this already lengthy request. I have read a little on how to build expression trees and how this translates in EF Core but I'm honestly lost as to where I would even intercept said expression tree to modify it for my goal. Any help here would be greatly appreciated.