0

I would like to retrieve the Type of entities that implement a specific interface. I want to retrive this inside the OnModelCreating method.

Example Assume that I have the following entity

public class Product : IProductBase {
   public int ProductId {get;set;}
}

I also have a entity that does not implement IProductBase for example:

Public class ProductInventory {
  public int Id {get;set;}
}

In the following onModelCreating I want to be able to retrieve all the Type(s) of entities that have implemented IProductBase interface.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{


}

I have tried few things such as trying to retrieve the ClrType. But that does not seem to work.

John
  • 583
  • 2
  • 7
  • 12
  • 1
    Try `var type = typeof(IProductBase ); var types = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(s => s.GetTypes()) .Where(p => type.IsAssignableFrom(p));` include namespaces `using System; using System.Linq;` – Vivek Nuna May 14 '18 at 10:49
  • 1 more question OnModelCreating is only called once right? – John May 14 '18 at 11:27
  • Once per each unique provider type. If you are targeting single database type (e.g. SqlServer), then it will be called once. Also, instead of iterating all the types in all assemblies, iterate just `modelBuilder.Mode.GetEntityTypes()` as shown here https://stackoverflow.com/questions/45096799/filter-all-queries-trying-to-achieve-soft-delete/45097532#45097532 – Ivan Stoev May 14 '18 at 11:40
  • @John it will be called when you do `Update-Database` means when you try to apply migration. Let me know if you need help – Vivek Nuna May 14 '18 at 11:45
  • @IvanStoev modelBuilder.Mode.GetEntityTypes() returns IMutableEntityType not the system.type which i need for reflection – John May 14 '18 at 12:33
  • Hi @IvanStoev tried following the question you linked. Getting following exception when ever I try to use the clrType property. exception System.MissingMethodException: 'Method not found: 'System.Type Microsoft.EntityFrameworkCore.Metadata.IEntityType.get_ClrType()'.' – John May 14 '18 at 12:43

1 Answers1

0

You can iterate the assemblies and get all the entities of type IProductBase.

using System;
using System.Linq;

var type = typeof(IProductBase ); 
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => type.IsAssignableFrom(p));

As suggested by @Ivan Stoev. You can also use the below method to get all the entities. Thank @Ivan for your valuable suggestions.

var type = modelBuilder.Model.GetEntityTypes(typeof(FullAuditedEntity));
Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197