TurnerSoftware / MongoFramework

An "Entity Framework"-like interface for MongoDB
MIT License
392 stars 35 forks source link

Common repo using reflection to find MongoDbSet #344

Closed DMGlion closed 1 year ago

DMGlion commented 1 year ago

Hi everyone this is just a question. We are using a common repo for all the common queries such find, update and remove by ID, we are doing that to avoid code duplication and repetition. To find the MongoDbSet collection we are using reflections due that we have multiple MongoDbSet collection on each context:

foreach(var prop in _context.GetType().GetProperties())
            {
                if (prop.PropertyType == typeof(MongoDbSet<T>))
                    return (MongoDbSet<T>) prop.GetValue(_context);
            }

This can slow down our application, is there any work around within MongoFramework to avoid to use reflection?

Turnerj commented 1 year ago

Hey @DMGlion - yeah, there's a method on the MongoDbContext called Set<TEntity>() so as long as you know your type (T in your case), you can just use that.

eg.

var myDbSet = _context.Set<T>();

The T doesn't actually have to be a property on the context either though if you do, it will reuse the same instance of the MongoDbSet.