-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEZmsContext.cs
59 lines (49 loc) · 1.73 KB
/
EZmsContext.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
59
using System;
using System.Linq;
using System.Threading.Tasks;
using EZms.Core.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
namespace EZms.Core
{
public class EZmsContext : IdentityDbContext
{
private const string SchemaName = "EZms";
public EZmsContext(DbContextOptions<EZmsContext> options) : base(options)
{
}
public DbSet<Content> Content { get; set; }
public DbSet<ContentVersion> ContentVersions { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema(schema: SchemaName);
modelBuilder.Entity<Content>()
.HasIndex("ParentId", "UrlSlug")
.IsUnique();
modelBuilder.Entity<ContentVersion>();
base.OnModelCreating(modelBuilder);
}
public bool Exists<T>(T entity) where T : class
{
return Set<T>().Local.Any(e => e == entity);
}
public async Task<int> SaveChangesAsync()
{
Audit();
return await base.SaveChangesAsync();
}
private void Audit()
{
var entries = ChangeTracker.Entries().Where(x => x.Entity is IContentData && (x.State == EntityState.Added || x.State == EntityState.Modified));
foreach (var entry in entries)
{
if (entry.State == EntityState.Added)
{
((IContentData)entry.Entity).CreatedAt = DateTime.UtcNow;
}
((IContentData)entry.Entity).UpdatedAt = DateTime.UtcNow;
}
}
}
}