首页 > 代码库 > ef 多个模块,通过程序集映射entity,指定对应的repository
ef 多个模块,通过程序集映射entity,指定对应的repository
在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); }
ef 多个模块,通过程序集映射entity,指定对应的repository
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。