using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;

namespace ex_042_007_ValueGeneration
{
    class NounoursDBEntities : DbContext
    {
        public DbSet<Nounours> NounoursSet { get; set; }

       
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
              optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=ex_042_007_ValueGeneration.Nounours.mdf;Trusted_Connection=True;");
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Nounours>().Property(n => n.Nom).HasDefaultValue("");
            modelBuilder.Entity<Nounours>().Property(n => n.DateDeNaissance).HasDefaultValue(DateTime.UtcNow);
            modelBuilder.Entity<Nounours>().Property(n => n.DateDInsertion).HasDefaultValue(DateTime.UtcNow);
            modelBuilder.Entity<Nounours>().Property(n => n.DernièreModification).HasDefaultValue(DateTime.UtcNow);

            base.OnModelCreating(modelBuilder);
        }

        public override int SaveChanges()
        {
            ChangeTracker.DetectChanges();

            foreach (var item in ChangeTracker.Entries<Nounours>().Where(e => e.State == EntityState.Added))
            {
                item.Property(n => n.DateDInsertion).CurrentValue = DateTime.UtcNow;
                item.Property(n => n.DernièreModification).CurrentValue = DateTime.UtcNow;
            }

            foreach (var item in ChangeTracker.Entries<Nounours>().Where(e => e.State == EntityState.Modified))
            {
                item.Property(n => n.DernièreModification).CurrentValue = DateTime.UtcNow;
            }
            return base.SaveChanges();
        }
    }
}
