一般来说,我如何包含限定在某个类中的实体的属性?

本文关键字:实体 属性 何包含 一般来说 | 更新日期: 2023-09-27 18:18:45

我使用实体框架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; }
}

UserRoleUserLocation也继承BaseEntity。我有一个通用的存储库接口IGenericRepository<TEntity> where TEntity : BaseEntityGenericRepository<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;
    }
}