Home > other >  How can i use SQL Server Functions with EF Core Power Tools
How can i use SQL Server Functions with EF Core Power Tools

Time:06-22

I am using EF Core Power Tools in my asp.net web application. After using it for a long time for my models and procedures, I wanted to use it for my existing database functions. I loaded the functions in the same way as the procedures and models in my project, when I wanted to call the functions with the following code I noticed that the generated functions are not implemented.I have searched the internet and have not found a way to use the functions from my SQL Server. Is there a way to load it with EF Core Power Tools?

How i want to call function

 var x = ASB_ZentralContext.GET_UST_Text(customerId, articleId);

Generated function code

 public partial class ZentralContext
   {

    [DbFunction("GET_UST_Satz", "dbo")]
    public static double? GET_UST_Satz(int? Zahler_ID, int? Artikel_ID)
    {
        throw new NotSupportedException("This method can only be called from Entity Framework Core queries");
    }

    [DbFunction("GET_UST_Text", "dbo")]
    public static string GET_UST_Text(int? Zahler_ID, int? Artikel_ID)
    {
        throw new NotSupportedException("This method can only be called from Entity Framework Core queries");
    }

    protected void OnModelCreatingGeneratedFunctions(ModelBuilder modelBuilder)
    {
    }
}

I tried id like this:

i added this in my DbContext

   public int Get_UST_Satz(int zahler_ID, int artikel_id)
 => throw new NotSupportedException();

and this in my dbContext ModelBuilder

modelBuilder.HasDbFunction(typeof(Context).GetMethod(nameof(Get_UST_Satz), new[] { typeof(int), typeof(int) }))
                .HasName("GET_UST_Satz");

CodePudding user response:

Your function returns a scalar value, so you cannot treat it as a table.

See the EF Core docs and the sample code in the Power Tools wiki

var result = db.Orders.Where(o => o.Reference == NorthWindContext.GetReference(o.OrderName)).ToList();
  • Related