-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathContext.cs
38 lines (28 loc) · 1.36 KB
/
Context.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Query.SqlExpressions;
using System;
using System.Linq;
namespace MRE.EFCore5.HasDbFunction
{
public class Context : DbContext
{
public Context(DbContextOptions dbContextOptions) : base(dbContextOptions) { }
public DbSet<Foo> Foos { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
var methodInfo = typeof(Extensions).GetMethod(nameof(Extensions.ToTimeZone));
static string DelimitIdentifier(string identifier) => $"[{identifier.Replace("]", "]]")}]";
modelBuilder
.HasDbFunction(methodInfo)
.HasTranslation(x =>
{
var columnExpression = x.First() as ColumnExpression;
var timeZoneExpression = x.Skip(1).First() as SqlConstantExpression;
var columnIdentifier = $"{DelimitIdentifier(columnExpression.Table.Alias)}.{DelimitIdentifier(columnExpression.Name)}";
var expression = new SqlFragmentExpression($"{columnIdentifier} AT TIME ZONE {timeZoneExpression.TypeMapping.GenerateSqlLiteral(timeZoneExpression.Value)}");
Console.WriteLine($"Translation => {expression.Sql}");
return expression;
});
}
}
}