CloudBuilder/CloudBuilder.Core/DependencyInjection/EFCore/RegistEntityHelper.cs
owenchen 1c0c83af5f ow
2026-05-12 10:09:31 +08:00

57 lines
2.0 KiB
C#

using CloudBuilder.Core.Authorization;
using CloudBuilder.Core.DatabaseAccessor.Entity;
using CloudBuilder.Core.Extensions;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace CloudBuilder.Core.DependencyInjection.EFCore
{
public class RegistEntityHelper
{
public static void AddMasterEntityType(ModelBuilder builder, string _assemblyName)
{
var eType = typeof(IEntity<>);
AddMasterEntityType(builder, _assemblyName, eType);
}
public static void AddSecondaryEntityType(ModelBuilder builder, string _assemblyName)
{
var eType = typeof(ISecondary);
AddMasterEntityType(builder, _assemblyName, eType);
}
public static void AddMasterEntityType(ModelBuilder builder, string _assemblyName, Type eType)
{
var mType = typeof(IEntity<>);
var sType = typeof(ISecondary);
var entityTypes = Assembly.Load(new AssemblyName(_assemblyName)).GetTypes()
.Where(type => !string.IsNullOrWhiteSpace(type.Namespace))
.Where(type => type.GetTypeInfo().IsClass)
.Where(type => type.GetTypeInfo().BaseType != null)
.Where(type => type.HasImplementedRawGeneric(eType)).ToList();
if (eType == mType) entityTypes = entityTypes.Where(type => !type.HasImplementedRawGeneric(sType)).ToList();
NotMappedAttribute notMapped = null;
foreach (var entityType in entityTypes)
{
//排除实体类标记[NotMapped]
notMapped = entityType.GetCustomAttribute<NotMappedAttribute>();
if (notMapped != null) continue;
if (builder.Model.FindEntityType(entityType) != null)
continue;
builder.Model.AddEntityType(entityType);
}
}
}
}