Skip to content

Instantly share code, notes, and snippets.

@danielplawgo
Created May 26, 2021 12:32
Show Gist options
  • Save danielplawgo/7a6773a452dd8ef3dc0e3321652912fd to your computer and use it in GitHub Desktop.
Save danielplawgo/7a6773a452dd8ef3dc0e3321652912fd to your computer and use it in GitHub Desktop.
Entity Framework Core - DbFunction
public class AuditLog
{
public Guid Id { get; set; } = Guid.NewGuid();
public DateTimeOffset Created { get; set; } = DateTimeOffset.UtcNow;
public string LogType { get; set; }
public string Data { get; set; }
}
public static class DatabaseFunctions
{
public static string JsonValue(string source, string path) => throw new NotSupportedException();
public static void Configure(ModelBuilder modelBuilder)
{
modelBuilder
.HasDbFunction(typeof(DatabaseFunctions).GetMethod(nameof(JsonValue)))
.HasTranslation(args => SqlFunctionExpression.Create("JSON_VALUE", args, typeof(string), null));
}
}
public class DataContext : DbContext
{
//pozostała zawartość
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
DatabaseFunctions.Configure(modelBuilder);
}
}
SELECT *
FROM [AuditLogs]
WHERE JSON_VALUE([Data], N'$.ProductId') = '1612D8E7-8A18-41AD-8BFA-100E1E2D3854'
private static async Task Show()
{
await using var db = new DataContext();
var logs = await db.AuditLogs
.Where(l => DatabaseFunctions.JsonValue(l.Data, "$.ProductId") == _productId.ToString())
.ToListAsync();
foreach (var auditLog in logs)
{
Console.WriteLine($"Log: {auditLog.LogType}, Date: {auditLog.LogType}, Data: {auditLog.Data}");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment