在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();
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 classTypeUtil
{public static IListGetEntityTypes()
{var cacheManager = newMemoryCacheManager();return cacheManager.Get("ENTITY-TYPE-ASSEMBLY", () =>{var typesToRegister =Assembly.GetExecutingAssembly().GetTypes()
.Where(type=> (typeof(BaseEntity).IsAssignableFrom(type) && (type.GetConstructor(Type.EmptyTypes) != null)));returntypesToRegister.ToList();
});
}
}
test:
[Test]public voidTypeUtilTest()
{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);
}