// Итого, сущности наследуем от Entity.
// Маппинги от BaseMap<TEntity> или EntityTypeConfiguration<TEntity>.
// В контексте тот же метод переопрделяем, что и в DemoAppDbContext.
// Достоинства - EF CF
// Маппинги в ондй сборке отдельно
// Нормальное интстанцирование маппингов черех один метод.
namespace DemoApp.Extensions
{
public static class TypeExtensions
{
public static bool IsAssignableFromGeneric(this Type t, Type type)
{
if (t == null)
{
throw new ArgumentNullException("t");
}
while (t.BaseType != null)
{
if (t.BaseType.IsGenericType && !t.BaseType.ContainsGenericParameters &&
t.BaseType.GetGenericTypeDefinition() == type)
{
return true;
}
t = t.BaseType;
}
return false;
}
}
}
namespace DemoApp.Data.Model.Contracts
{
// Базовый интерфейс для всех сущностей, хранимых в базе.
public interface IEntity
{
Guid Id { get; set; }
bool IsTransient { get; }
}
}
namespace DemoApp.Data.Model.Entities
{
// Базовый класс для всех сущностей, хранимых в базе.
public abstract class Entity : IEntity
{
// TODO: Поменять на int?
public Guid Id { get; set; }
public bool IsTransient
{
get { return this.Id == Guid.Empty; }
}
}
}
namespace DemoApp.Data.EntityFramework.Mappings
{
// Базовый класс для большинства маппингов, для остальных EntityTypeConfiguration<TEntity>
public abstract class BaseMap<TEntity> : EntityTypeConfiguration<TEntity> where TEntity : class, IEntity
{
protected BaseMap()
{
this.HasKey(t => t.Id);
this.Property(t => t.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
}
}
}
namespace DemoApp.Data.EntityFramework.DataContexts
{
public class DemoAppDbContext : DbContext
{
#region Constructor
public OlympiatoppenDbContext([NotNull] string nameOrConnectionString)
: base(nameOrConnectionString, validationMessages)
{
}
#endregion
#region DbSets
#endregion
#region Overrides of DbContext
protected override void OnModelCreating([NotNull] DbModelBuilder modelBuilder)
{
var modelConfigurationTypes = typeof (BaseMap<>).Assembly.GetTypes()
.Where(type => !type.IsAbstract && type.IsAssignableFromGeneric(typeof (EntityTypeConfiguration<>)));
foreach (dynamic configuration in modelConfigurationTypes.Select(Activator.CreateInstance))
{
modelBuilder.Configurations.Add(configuration);
}
base.OnModelCreating(modelBuilder);
}
}
}