﻿// MIT License. Copyright (c) 2016 Maxim Kuzmin. Contacts: https://github.com/maxim-kuzmin

// Author: Maxim Kuzmin

using Makc2016.Data.Entity.Objects;
using Makc2016.Data.Objects;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
using System.Data.Entity.ModelConfiguration.Configuration;

namespace Makc2016.Data.Entity.Configs
{
    /// <summary>
    /// Данные. Entity Framework. Конфигурации. Конфигурация данных сущности "Role".
    /// </summary>
    public class DataEntityConfigRole : EntityTypeConfiguration<DataEntityObjectRole>
    {
        #region Constructors

        /// <summary>
        /// Конструктор.
        /// </summary>
        public DataEntityConfigRole()
        {
            ToTable(DataObjectRole.DB_TABLE_NAME, DataObjectRole.DB_SCHEMA_NAME);

            HasKey(x => x.Id);

            Property(x => x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);           
            Property(x => x.Name).IsRequired().IsVariableLength().IsUnicode().HasMaxLength(50);

            HasMany(x => x.ObjectsUser)
                .WithMany(x => x.ObjectsRole)
                .Map(x => MapUserRole(x));
        }

        #endregion Constructors

        #region Private methods

        private void MapUserRole(ManyToManyAssociationMappingConfiguration config)
        {
            config.MapLeftKey("RoleId");
            config.MapRightKey("UserId");

            config.ToTable(
                DataObjectUserRole.DB_TABLE_NAME,
                DataObjectUserRole.DB_SCHEMA_NAME
                );
        }

        #endregion Private methods
    }
}
