|
| 1 | +using System; |
| 2 | +using System.Reflection; |
| 3 | +using System.Linq; |
| 4 | +using System.Linq.Expressions; |
| 5 | +using JsonApiDotNetCore.Extensions; |
| 6 | +using Microsoft.EntityFrameworkCore; |
| 7 | + |
| 8 | +namespace JsonApiDotNetCore.Data |
| 9 | +{ |
| 10 | + public class GenericDataAccessAbstraction |
| 11 | + { |
| 12 | + private GenericDataAccess _dataAccessorInstance; |
| 13 | + private DbContext _dbContext; |
| 14 | + private Type _modelType; |
| 15 | + private string _includedRelationship; |
| 16 | + public GenericDataAccessAbstraction(object dbContext, Type modelType, string includedRelationship) |
| 17 | + { |
| 18 | + _dataAccessorInstance = (GenericDataAccess)Activator.CreateInstance(typeof(GenericDataAccess)); |
| 19 | + _dbContext = (DbContext) dbContext; |
| 20 | + _modelType = modelType; |
| 21 | + _includedRelationship = includedRelationship?.ToProperCase(); |
| 22 | + } |
| 23 | + |
| 24 | + public object SingleOrDefault(string id) |
| 25 | + { |
| 26 | + var dbSet = GetDbSet(); |
| 27 | + if (!string.IsNullOrEmpty(_includedRelationship)) |
| 28 | + { |
| 29 | + dbSet = IncludeRelationshipInContext(dbSet); |
| 30 | + } |
| 31 | + var dataAccessorSingleOrDefaultMethod = _dataAccessorInstance.GetType().GetMethod("SingleOrDefault"); |
| 32 | + var genericSingleOrDefaultMethod = dataAccessorSingleOrDefaultMethod.MakeGenericMethod(_modelType); |
| 33 | + return genericSingleOrDefaultMethod.Invoke(_dataAccessorInstance, new[] { dbSet, "Id", id }); |
| 34 | + } |
| 35 | + |
| 36 | + private object GetDbSet() |
| 37 | + { |
| 38 | + var dataAccessorGetDbSetMethod = _dataAccessorInstance.GetType().GetMethod("GetDbSet"); |
| 39 | + var genericGetDbSetMethod = dataAccessorGetDbSetMethod.MakeGenericMethod(_modelType); |
| 40 | + return genericGetDbSetMethod.Invoke(_dataAccessorInstance, new [] { _dbContext }); |
| 41 | + } |
| 42 | + |
| 43 | + private object IncludeRelationshipInContext(object dbSet) |
| 44 | + { |
| 45 | + var includeMethod = _dataAccessorInstance.GetType().GetMethod("IncludeEntity"); |
| 46 | + var genericIncludeMethod = includeMethod.MakeGenericMethod(_modelType); |
| 47 | + return genericIncludeMethod.Invoke(_dataAccessorInstance, new []{ dbSet, _includedRelationship }); |
| 48 | + } |
| 49 | + |
| 50 | + } |
| 51 | +} |
0 commit comments