using MapToStoredProcedure.Model;
using System.Data.Entity;

namespace MapToStoredProcedure.Context
{
    /// <summary>
    /// Context contains two tables Employee and Department
    /// these two tables are related with each other in 1...n relation
    /// One Department can have multiple Employees
    /// One Employee can be related to only one Department
    /// </summary>
    public class PSQLDbContext : DbContext
    {
        public PSQLDbContext()
        {
            // Set Initializer
            // Drop and Create Database Always
            // This is to ensure we get a fresh database always we run this application
            Database.SetInitializer(new DropCreateDatabaseAlways<PSQLDbContext>());
        }

        public DbSet<Department> Departments { get; set; }
        public DbSet<Employee> Employees { get; set; }

        /// <summary>
        /// Overriding to enable Mapping to stored procedure
        /// </summary>
        /// <param name="modelBuilder"></param>
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            // Mapping to stored procedures
            modelBuilder.Entity<Employee>().MapToStoredProcedures(x =>
                                            x.Insert(i => i.HasName("Employee_InsertSP"))
                                             .Update(u => u.HasName("Employee_UpdateSP"))
                                             .Delete(d => d.HasName("Employee_DeleteSP")));

            modelBuilder.Entity<Department>().MapToStoredProcedures(x =>
                                              x.Insert(i => i.HasName("Department_InsertSP"))
                                               .Update(u => u.HasName("Department_UpdateSP"))
                                               .Delete(d => d.HasName("Department_DeleteSP")));

            base.OnModelCreating(modelBuilder);
        }
    }
}
