﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace ManagerShop.Data.DbContent
{
    public class BaseDbContext : DbContext
    {
        public BaseDbContext() : base("AWSShopManagerDB")
        {
            this.Configuration.ValidateOnSaveEnabled = false;

            #region LazyLoadの設定、TRUEの場合、LazyLoadを行う、且つvirtualに追加する
            this.Configuration.LazyLoadingEnabled = true; // 延迟加载不启用
            #endregion

            this.Configuration.ProxyCreationEnabled = true; // 代理追踪不启用


            //変更する場合、データ状態の表示、
            //例えば新規(Added State),修正(Modified State),
            //削除(Deleted State),Unchanged State
            this.Configuration.AutoDetectChangesEnabled = true;

            var ensureDLLIsCopied =
                System.Data.Entity.SqlServer.SqlProviderServices.Instance;

        }

        /// <summary>
        /// DB=>Mapping設定
        /// </summary>
        /// <param name="modelBuilder"></param>
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            //default設定
            //modelBuilder.Entity<User>().HasKey(t => t.Id);

            // override EntityTypeConfiguration<EntityType>

            //全部テーブルのschemaを設定する
            //modelBuilder.HasDefaultSchema("newdbo");

            string assembleFileName = Assembly.GetExecutingAssembly().CodeBase.Replace("ManagerShop.Data.DbContent", "ManagerShop.Data.Mapping").Replace("file:///", "");
            Assembly asm = Assembly.LoadFile(assembleFileName);
            var typesToRegister = asm.GetTypes()
                .Where(type => !String.IsNullOrEmpty(type.Namespace))
                .Where(type => type.BaseType != null && type.BaseType.IsGenericType && type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>));
            foreach (var type in typesToRegister)
            {
                dynamic configurationInstance = Activator.CreateInstance(type);
                modelBuilder.Configurations.Add(configurationInstance);
            }
        }
    }
}
