在Entity Framework repository下加两个方法:
public virtual T GetByEntityName(object id, string EntityTypeName) { dynamic repository = GetEFRepository(EntityTypeName); if (repository != null) return repository.Entities.Find(id); else return null; } public virtual dynamic GetRecordRepository(string EntityTypeName) { dynamic repository = GetEFRepository(EntityTypeName); if (repository != null) { var type = repository.GetType().GetGenericArguments()[0]; dynamic part = Activator.CreateInstance(type); return part; } else { return null; } } private object GetEFRepository(string EntityTypeName) { if (_repositoryDictionary == null) { var typesToRegister = TypeUtil.GetEntityTypes(); _repositoryDictionary = new Dictionary<string, object>(); foreach (var type in typesToRegister) { object repository = Activator.CreateInstance(typeof(EfRepository<>).MakeGenericType(type), _context); _repositoryDictionary[type.Name] = repository; } } if (_repositoryDictionary.ContainsKey(EntityTypeName)) return _repositoryDictionary[EntityTypeName]; else return null; }
TypeUtil.cs
public class TypeUtil { public static IList<Type> GetEntityTypes() { var cacheManager = new MemoryCacheManager(); return cacheManager.Get("ENTITY-TYPE-ASSEMBLY", () => { var typesToRegister = Assembly.GetExecutingAssembly().GetTypes() .Where(type => (typeof(BaseEntity).IsAssignableFrom(type) && (type.GetConstructor(Type.EmptyTypes) != null))); return typesToRegister.ToList(); }); } }
test:
[Test] public void TypeUtilTest() { var n = _repository.GetRecordRepository("NewsEntity"); dynamic nm = _repository.GetByEntityName(1, "NewsEntity"); var title = nm.Title; var c = _repository.GetRecordRepository("NewsCommentEntity"); dynamic cm = _repository.GetByEntityName(1, "NewsCommentEntity"); var comment = cm.Comment; string pass = title + "\n" + comment; Assert.Pass(pass); }
时间: 2024-11-15 19:33:55