Search code examples
c#sqllinqentity-framework-coreef-core-8.0

Is it possible to call a scalar function in entity framework?


I have a scalar function that takes 2 parameters and returns an integer.

In sql I can call the function by simply including it in my sql statement. IE

select funcname(dateparamfrom, 
dateparamto) as numholidays from table

My question is as part of a linq entity framework 8 join query how to I include that scalar function call in my query.

I have 2 model classes for 2 tables and I am able to join those but the query in question uses a scalar function to return a number based on how the function is written, EF 8.

Var data from context.dbtbale name

I know you can use the context.sqlquery method but is this the correct way?

Thanks


Solution

  • You can map your own functions using EF Core. To do this you need to configure your DbContext, for example:

    public class MyContext : DbContext
    {
        // This is a stub method used only by EF
        public int GetDayCount(DateTime from, DateTime to)
            => throw new InvalidOperationException();
    
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            // Now map the stub method into a call in the database
            modelBuilder
                .HasDbFunction(
                    typeof(MyContext).GetMethod(nameof(GetDayCount),
                        new[] { typeof(DateTime), typeof(DateTime) })!)
                .HasName("NameOfFunctionInDatabase");
    
            base.OnModelCreating(modelBuilder);
        }
    
    
        public DbSet<Meeting> Meetings { get; set; }
    }
    

    Now you can use the function like this:

    var result = context.Users
        .Where(m => context.GetDayCount(m.From, m.To) > 5)
        .ToList();
    

    See the docs for more detail