Created
May 26, 2021 12:32
-
-
Save danielplawgo/7a6773a452dd8ef3dc0e3321652912fd to your computer and use it in GitHub Desktop.
Entity Framework Core - DbFunction
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; } | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class DataContext : DbContext | |
{ | |
//pozostała zawartość | |
protected override void OnModelCreating(ModelBuilder modelBuilder) | |
{ | |
base.OnModelCreating(modelBuilder); | |
DatabaseFunctions.Configure(modelBuilder); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SELECT * | |
FROM [AuditLogs] | |
WHERE JSON_VALUE([Data], N'$.ProductId') = '1612D8E7-8A18-41AD-8BFA-100E1E2D3854' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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