Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion DJT.EntityFrameworkCore/DJT.EntityFrameworkCore.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.28" />
</ItemGroup>

</Project>
23 changes: 11 additions & 12 deletions DJT.EntityFrameworkCore/DbContextExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,24 +21,23 @@ public static class DbContextExtensions
/// If entities are internal, the assembly attribute <see cref="InternalsVisibleToAttribute"/> may
/// need specifying.
/// </summary>
/// <param name="dbContext"></param>
/// <param name="modelBuilder"></param>
public static void UseSelfDefiningModels(this DbContext dbContext, ModelBuilder modelBuilder)
public static void UseSelfDefiningModels(this ModelBuilder modelBuilder)
{
Type dbContextType = dbContext.GetType();
foreach (var prop in dbContextType.GetProperties())
var entities = modelBuilder.Model.GetEntityTypes();
foreach (var entity in entities)
{
var propType = prop.PropertyType;
if (propType.IsGenericType && propType.GetGenericTypeDefinition() == typeof(DbSet<>))
modelBuilder.Entity(entity.Name, builder =>
{
var itemType = propType.GenericTypeArguments[0];//.GetGenericTypeDefinition().GetGenericArguments()[0];
var method = itemType.GetMethod("OnModelCreating");
if (typeof(ISelfDefine).IsAssignableFrom(itemType) && method != null)
Type itemType = entity.ClrType;

var method = itemType.GetMethod(nameof(ISelfDefine.OnModelCreating));
if (typeof(ISelfDefine).IsAssignableFrom(itemType) && method is not null)
{
//If the "OnModelCreating(ModelBuilder modelBuilder)" method exists, run it with the given ModelBuilder
method.Invoke(Activator.CreateInstance(itemType, false), new object[] { modelBuilder });
method.Invoke(Activator.CreateInstance(itemType, false),
new object[] { modelBuilder });
}
}
});
}
}
}
Expand Down