using CustomCodeFirstConventions.Model;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CustomCodeFirstConventions.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>
        /// Overridden to create Custom Code First Conventions
        /// </summary>
        /// <param name="modelBuilder"></param>
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            // Changing the Key criteria
            // Any property containing keyword 'key' can be a key attribute for a table
            modelBuilder
                .Properties()
                .Where(p => p.Name.Contains("Key") || p.Name.Contains("key"))
                .Configure(p => p.IsKey());

            // Changing default length for string attributes
            // setting default value to 30
            modelBuilder
                .Properties<string>()
                .Configure(p => p.HasMaxLength(30));
        }
    }
}
