From 001e78736ccad3858f8108f7b7ae5197b6f007cd Mon Sep 17 00:00:00 2001 From: Kevin Matsubara Date: Tue, 8 Apr 2025 22:35:20 +0200 Subject: [PATCH] Add example user-defined function. --- EntityFrameworkCore.Console/Program.cs | 15 +++++++++++++++ .../DeadBallZoneLeagueDbContext.cs | 11 +++++++++++ 2 files changed, 26 insertions(+) diff --git a/EntityFrameworkCore.Console/Program.cs b/EntityFrameworkCore.Console/Program.cs index e9552a6..50bcd48 100644 --- a/EntityFrameworkCore.Console/Program.cs +++ b/EntityFrameworkCore.Console/Program.cs @@ -17,6 +17,21 @@ context.Database.EnsureCreated(); // var firstCoach = await context.Coaches.FirstOrDefaultAsync(); +async Task UserDefinedQuery() +{ + var earliestMatch = context.GetEarliestTeamMatch(1); + // This is done, if you have a user-defined function in the database. + // for example: + // CREATE FUNCTION [dbo].[GetEarliestMatch] (@teamId int) + // RETURNS datetime + // BEGIN + // DECLARE @result datetime + // SELECT TOP 1 @result = date + // FROM MATCHES [dbo].[Matches] + // ORDER BY Date + // return @result + // END +} async Task QueryScalarType() { diff --git a/EntityFrameworkCore.Data/DeadBallZoneLeagueDbContext.cs b/EntityFrameworkCore.Data/DeadBallZoneLeagueDbContext.cs index d539fa9..f8dc8dc 100644 --- a/EntityFrameworkCore.Data/DeadBallZoneLeagueDbContext.cs +++ b/EntityFrameworkCore.Data/DeadBallZoneLeagueDbContext.cs @@ -41,5 +41,16 @@ public class DeadBallZoneLeagueDbContext : DbContext // This database object does not have a Primary Key, so we state that here, otherwise an exception is thrown. modelBuilder.Entity().HasNoKey().ToView("vw_TeamsAndLeagues"); + + // This is for user-defined functions. + modelBuilder.HasDbFunction( + typeof(DeadBallZoneLeagueDbContext) + .GetMethod( + nameof(GetEarliestTeamMatch), + new[] {typeof(int)} + )) + .HasName("GetEarliestMatch"); } + + public DateTime GetEarliestTeamMatch(int teamId) => throw new NotImplementedException(); }