Files
juipnet/Infrastructure/Hncore.Infrastructure/EF/Extensions/AutoMap.cs
“wanyongkang” ed3b2c653e 接口文件
2024-04-10 13:55:27 +08:00

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);
}
}
}
}