47 lines
1.6 KiB
C#
47 lines
1.6 KiB
C#
using System;
|
|
using System.Collections.Concurrent;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Reflection;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
namespace Hncore.Infrastructure.EF
|
|
{
|
|
public static class AutoMapExtensions
|
|
{
|
|
private static object syncRoot = new object();
|
|
private static ConcurrentDictionary<IEntityMap, object> maps;
|
|
|
|
public static void AutoMap(this ModelBuilder modelBuilder, Type assType)
|
|
{
|
|
if (maps == null)
|
|
{
|
|
lock (syncRoot)
|
|
{
|
|
if (maps == null)
|
|
{
|
|
maps = new ConcurrentDictionary<IEntityMap, object>();
|
|
|
|
Type mappingInterface = typeof(IEntityMap<>);
|
|
|
|
var mappingTypes = assType.GetTypeInfo().Assembly.GetTypes()
|
|
.Where(x => !x.IsAbstract
|
|
&& x.GetInterfaces().Any(y => y.GetTypeInfo().IsGenericType
|
|
&& y.GetGenericTypeDefinition() ==
|
|
mappingInterface));
|
|
|
|
foreach (var map in mappingTypes.Select(Activator.CreateInstance).Cast<IEntityMap>())
|
|
{
|
|
maps.TryAdd(map, null);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
foreach (var map in maps.Keys)
|
|
{
|
|
map.Map(modelBuilder);
|
|
}
|
|
}
|
|
}
|
|
} |