forked from dotnetzoom/AspNetCore-WebApi-Course
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApplicationDbContext.cs
92 lines (78 loc) · 3.09 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
using Common.Utilities;
using Entities;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
namespace Data
{
public class ApplicationDbContext : IdentityDbContext<User, Role, int>
//DbContext
{
public ApplicationDbContext(DbContextOptions options)
: base(options)
{
}
//protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
//{
// optionsBuilder.UseSqlServer("Data Source=.;Initial Catalog=MyApiDb;Integrated Security=true");
// base.OnConfiguring(optionsBuilder);
//}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
var entitiesAssembly = typeof(IEntity).Assembly;
modelBuilder.RegisterAllEntities<IEntity>(entitiesAssembly);
modelBuilder.RegisterEntityTypeConfiguration(entitiesAssembly);
modelBuilder.AddRestrictDeleteBehaviorConvention();
modelBuilder.AddSequentialGuidForIdConvention();
modelBuilder.AddPluralizingTableNameConvention();
}
public override int SaveChanges()
{
_cleanString();
return base.SaveChanges();
}
public override int SaveChanges(bool acceptAllChangesOnSuccess)
{
_cleanString();
return base.SaveChanges(acceptAllChangesOnSuccess);
}
public override Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default)
{
_cleanString();
return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
}
public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
{
_cleanString();
return base.SaveChangesAsync(cancellationToken);
}
private void _cleanString()
{
var changedEntities = ChangeTracker.Entries()
.Where(x => x.State == EntityState.Added || x.State == EntityState.Modified);
foreach (var item in changedEntities)
{
if (item.Entity == null)
continue;
var properties = item.Entity.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(p => p.CanRead && p.CanWrite && p.PropertyType == typeof(string));
foreach (var property in properties)
{
var propName = property.Name;
var val = (string)property.GetValue(item.Entity, null);
if (val.HasValue())
{
var newVal = val.Fa2En().FixPersianChars();
if (newVal == val)
continue;
property.SetValue(item.Entity, newVal, null);
}
}
}
}
}
}