0

I have this kind of requirement as there are around 100+ model classes.

I have repository pattern implemented for database operations:

public class interface IRepository<TEntity> : IRepository<TEntity>where TEntity : class

It has a method Task Add(TEntity entity);

Under normal circumstances, I would just do this if I want to add UserClass model to DB

public class UserClass { string Name }
    
UserClass userClassObj = new UserClass { Name = "John" }

await Repository <UserClass>.Add(userClassObj);

However, my requirement is to pass pass class type dynamically based on condition as i have around 100+ models.

if (condition == "1")
   classtype = USerClass
else if (condition == "2")
   classtype = DepartmentClass
else if (condition == "3")
   classtype = CategoryClass

and then pass classtype to the repository

await Repository <classtype>.Add(object of (classtype ));

Is this doable? Any working example will be highly appreciated. Could not find straight forward implementation so far.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Dev
  • 93
  • 8

2 Answers2

1

You might need to extend your class definition like this,

public class interface IRepository<TEntity> : IRepository<TEntity>where TEntity : class, new()

new() enables creating new object based on passed type.

then you can call it like this,

if (condition == "1")
   await Repository<USerClass>.Add(object);
else if (condition == "2")
   await Repository<DepartmentClass>.Add(object);
Yogesh
  • 1,565
  • 1
  • 19
  • 46
0

If you don't want to use Reflection may add an extra add helper method to (maybe also to your IRepositoryType not sure if this<T> work)

 public static async Task Add<T>(T objectToAdd) where T : TEntity
 {
    await Repository<T>.Add(objectToAdd)
 }

if you have the type argument and a parameter that needs the type you dont have to specify it any more and it will chosoe usually the right type argument with the given parameter type. E.g.

var userObject = new UserObject();
Repository.Add(userObject);

will automaticly detect that it is the userbject the type to be add

another possibility would be to use a Dictionary<Type,yourDBsetType>() and match it by the type key

Mucksh
  • 160
  • 5
  • This doesn't work because the OP has a reference to his type that is not for the type itself. It'd be like `object instance = new UserObject();` If you call `Respository.Add(instance)` the inferred type would be `object`. – Enigmativity Oct 10 '21 at 08:20