-
-
Notifications
You must be signed in to change notification settings - Fork 348
/
Copy pathApplicationDbContext.cs
58 lines (55 loc) · 2.17 KB
/
ApplicationDbContext.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
using Application.Interfaces;
using Domain.Common;
using Domain.Entities;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Infrastructure.Persistence.Contexts
{
public class ApplicationDbContext : DbContext
{
private readonly IDateTimeService _dateTime;
private readonly IAuthenticatedUserService _authenticatedUser;
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, IDateTimeService dateTime, IAuthenticatedUserService authenticatedUser) : base(options)
{
ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
_dateTime = dateTime;
_authenticatedUser = authenticatedUser;
}
public DbSet<Product> Products { get; set; }
public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken())
{
foreach (var entry in ChangeTracker.Entries<IAuditableEntity>())
{
switch (entry.State)
{
case EntityState.Added:
entry.Entity.Created = _dateTime.NowUtc;
entry.Entity.CreatedBy = _authenticatedUser.UserId;
break;
case EntityState.Modified:
entry.Entity.LastModified = _dateTime.NowUtc;
entry.Entity.LastModifiedBy = _authenticatedUser.UserId;
break;
}
}
return base.SaveChangesAsync(cancellationToken);
}
protected override void OnModelCreating(ModelBuilder builder)
{
//All Decimals will have 18,6 Range
foreach (var property in builder.Model.GetEntityTypes()
.SelectMany(t => t.GetProperties())
.Where(p => p.ClrType == typeof(decimal) || p.ClrType == typeof(decimal?)))
{
property.SetColumnType("decimal(18,6)");
}
base.OnModelCreating(builder);
}
}
}