using Microsoft.EntityFrameworkCore; using System; using System.Linq; namespace EFCoreTest { public class MyDbContext : DbContext { protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { //optionsBuilder.UseSqlite("Data Source=data.db;"); //optionsBuilder.UseMySql("Server=139.180.143.95;Port=3306;Database=test;Uid=admin;Pwd=admin;"); ///https://www.cockroachlabs.com/docs/stable/build-a-csharp-app-with-cockroachdb.html /// cockroach start --insecure --host=localhost --http-port=9090 /// cockroach sql --insecure /// CREATE DATABASE test; /// DROP DATABASE test CASCADE; /// \q optionsBuilder.UseNpgsql("User ID=root;Host=localhost;Port=26257;Database=test;"); } protected override void OnModelCreating(ModelBuilder modelBuilder) { foreach (var entity in modelBuilder.Model.GetEntityTypes()) { if (entity.GetProperties().Any(o => o.Name == "Id")) { modelBuilder.Entity(entity.Name).HasKey("Id"); modelBuilder.Entity(entity.Name).Property("Id").ValueGeneratedNever(); } if (entity.GetProperties().Any(o => o.Name == "RowVersion")) { modelBuilder.Entity(entity.Name).Property("RowVersion")?.IsConcurrencyToken().ValueGeneratedNever(); } } modelBuilder.Entity().Property(o => o.UserName).IsRequired().HasMaxLength(64); modelBuilder.Entity().Property(o => o.Name).IsRequired().HasMaxLength(64); ; modelBuilder.Entity().HasOne(o => o.User).WithMany(o => o.UserRoles).HasForeignKey(o => o.UserId); modelBuilder.Entity().HasOne(o => o.Role).WithMany(o => o.UserRoles).HasForeignKey(o => o.RoleId); modelBuilder.Entity().HasIndex(o => new { o.UserId, o.RoleId }).IsUnique(); } public override int SaveChanges() { var entries = this.ChangeTracker.Entries().ToList(); foreach (var entry in entries) { if (entry.State == EntityState.Added || entry.State == EntityState.Modified) { var now = DateTime.UtcNow; if (entry.State == EntityState.Added) { if (entry.Properties.Any(o => o.Metadata.Name == "Created")) { entry.Property("Created").CurrentValue = now; } } if (entry.Properties.Any(o => o.Metadata.Name == "RowVersion")) { entry.Property("RowVersion").CurrentValue = Guid.NewGuid().ToString(); } if (entry.Properties.Any(o => o.Metadata.Name == "LastChanged")) { entry.Property("LastChanged").CurrentValue = now; } } Console.WriteLine($"id:{entry.Entity.ToString()},state:{entry.State}"); } return base.SaveChanges(); } } }