jeudi 3 novembre 2022

How get class by name with generic or how correct realize this problem?

I want dinamycally load catalogs to DevExpress grid and repositories. Some columns reference to other tables. I want to realize without "if-else, switch" methods, solve with generic for example. My project consists of entity framework, unitofwork etc.

RepositoryItemLookUpEdit repositoryItemLookUpEdit = new RepositoryItemLookUpEdit()
{
  ValueMember = repositoryItem.ValueMember,
  DisplayMember = repositoryItem.DisplayMember
;
// var objectType = GetTypeByName(repositoryItem.FinalTable);
if (repositoryItem.FinalTable=="DeviceTypes")
{
  objectList = GetObjectList<DeviceTypes>();
}
else if (repositoryItem.FinalTable == "DeviceKinds")
{
objectList = GetObjectList<DeviceKinds>();
}
 repositoryItemLookUpEdit.DataSource = objectList;
 bandedGridColumn.ColumnEdit = repositoryItemLookUpEdit;
---
private IEnumerable<T> GetObjectList <T>() where T : Entity
{
  IEnumerable<T> objectList=Enumerable.Empty<T>();
  using (var unitOfWork = new UnitOfWork(new ApplicationDbContext(optionsBuilder.Options)))
  {
     objectList = unitOfWork.GetRepository<T>().GetAll();
  }
  return objectList;
}
---
private T GetTypeByName<T>(string typeName) where T:Entity
{
   foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies().Reverse())
   {
      var type = assembly.GetType(typeName);
      if (type != null)
      {
         return type as T;
      }
   }
return null;
}




Aucun commentaire:

Enregistrer un commentaire