Call a SQL function in EF Core 3 without Linq queries, mapping and translation

rramname

Rohit Ramname

Posted on October 1, 2020

Call a SQL function in EF Core 3 without Linq queries, mapping and translation

I have come across couple scenarios where I need to call an already existing scalar function in SQL server that has some logic into my C# EF Core 3 application for reusability. But most the guides out there show how can this be done only by mapping it to a C# function with Throw new Notimplemented exception and using Linq queries like official documentation.
I did not need to use Linq queries so I am doing it in a different way as below.

Letโ€™s say you have a SQL function.

CREATE FUNCTION dbo.IsStrogestAvenger(@Superhero varchar(100))
RETURNS bit
AS
BEGIN
    declare @result bit=0
    if(@Superhero ='Thor')
        set @result=1
    else
        set @result=0
RETURN @result
END
Enter fullscreen mode Exit fullscreen mode


`

Now turn to our C# code.
For result, lets create a model to hold this output.

`

public class IsStrongestAvengerResult
{
   public bool IsStrongestAvenger { get; set; }
}
Enter fullscreen mode Exit fullscreen mode


`

Map it in context class as below

`

public virtual DbSet<IsStrongestAvengerResult> IsStrongestAvenger{ get; set; }
Enter fullscreen mode Exit fullscreen mode


`

And

`

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<IsStrongestAvengerResult>(e => e.HasNoKey());
}
Enter fullscreen mode Exit fullscreen mode


`

Now we use FromSqlInterpolated to call this function and map.

`

public bool IsStrongestAvenger(string Superhero)
  {
    return context.IsStrongestAvenger.FromSqlInterpolated($"select   dbo.IsStrogestAvenger ({Superhero}) as IsStrongestAvenger").FirstOrDefault().IsStrongestAvenger;
}
Enter fullscreen mode Exit fullscreen mode


`

Important thing to note above is the use of AS >IsStrongestAvenger and it should match with the property name in >our model IsStrongestAvengerResult.IsStrongestAvenger

Now this function can be directly call from C# to get the output.

Thank you for reading. Comments and Suggestion are highly appreciated.

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
rramname
Rohit Ramname

Posted on October 1, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About