我正在将Entity Framework 6.x与T4模板一起使用,以从DbContext
生成我的.edmx
和实体类。我所有的实体都继承了一个名为BaseEntity
的类。以以下示例实体为例:
public partial class UserEntity : BaseEntity {
[IdentityColumn]
public int Id { get; set; }
public string Name { get; set; }
public int fkUserLocationId { get; set; }
[NavigationColumn]
public virtual ICollection<UserRole> UserRoles { get; set; }
[NavigationColumn]
public virtual UserLocation UserLocation { get; set; }
}
UserRole
和UserLocation
也继承BaseEntity
。我有一个通用的存储库接口IGenericRepository<TEntity> where TEntity : BaseEntity
和该GenericRepository<TEntity> where TEntity: BaseEntity
的实现:public class GenericRepository<TEntity> : IGenericRepository<TEntity> where TEntity : BaseEntity {
protected readonly MyDbContext _context;
protected readonly DbSet<T> _dbSet;
public GenericRepository(MyDbContext context) {
_context = context;
_dbSet = context.Set<T>();
}
//Would like to limit object to be of type BaseEntity or ICollection<BaseEntity>
public IQueryable<TEntity> Get(params Expression<Func<TEntity, object>>[] includeProperties)
{
var query = _dbSet.AsQueryable();
foreach (var include in includeProperties){
query = query.Include(include);
}
return query;
}
}
有了这些,我可以通过执行以下操作轻松地包含实体:
//Assume this repository already exists
_userRepository.Get(user => user.UserRoles, user => user.UserLocation); //Valid include
_userRepository.Get(user => user.Name); //Invalid include but appears in Intellisense
如何正确定义此方法,以确保只有
BaseEntity
属性(或具有NavigationColumn
属性的属性)在该Func
中有效? 最佳答案
public class GenericRepository<TEntity> : IGenericRepository<TEntity> where TEntity : BaseEntity {
protected readonly MyDbContext _context;
protected readonly DbSet<T> _dbSet;
public GenericRepository(MyDbContext context) {
_context = context;
_dbSet = context.Set<T>();
}
//Would like to limit object to be of type BaseEntity or ICollection<BaseEntity>
public IQueryable<TEntity> Get(params Expression<Func<TEntity, object>>[] includeProperties)
{
var query = _dbSet.AsQueryable();
//Something like that may help? wont solve the issue of intelisense knowing what is allowed and what is not allowed.
includeProperties = includeProperties.Where(p=>p.Type.DeclaringType.GetCustomAttributes(typeof(NavigationProperty),true).Any());
foreach (var include in includeProperties){
query = query.Include(include);
}
return query;
}
}