获取具有通用存储库基础的导航属性 class

Get a Navigational properties with generic Repository Base class

我有一个存储库基础 class 像这样:

public abstract class RepositoryBase<T> : IRepositoryBase<T> where T : class
{
    protected RepositoryContext RepositoryContext;

    public RepositoryBase(RepositoryContext repositoryContext)
        => RepositoryContext = repositoryContext;

         public IQueryable<T> FindByCondition(Expression<Func<T, bool>> 
    expression, bool trackChanges)
            {
                return !trackChanges ?
                  RepositoryContext.Set<T>().Where(expression).AsNoTracking() :
                            RepositoryContext.Set<T>().Where(expression);
            }
}

这可以很好地检索单个实体。但是我怎样才能修改它来检索它的导航属性呢?

我在 Whosebug 上看到了这种答案。但我不知道如何将它应用到我上面的基础class。请帮忙。

    RepositoryContext.Model.GetEntityTypes()
                         .Select(t => new
                         {
                             t.ClrType.Name,
                             NavigationProperties = t.GetNavigations()
.Select(x => x.PropertyInfo)
                     });

我的查询是这样的:

     public async Task<IEnumerable<Fare>> 
GetAllFaresByUserAsync(string userId, bool trackChanges)
            {
                return await FindByCondition(e => e.UserId.Equals(userId), 
    trackChanges).ToListAsync();
            }

模型是这样的:我可以使用上面的查询获取 Fares 集合。但是 "extras": [], 是这里的问题吗?

Fare

public class Fare
{
    [Column("FareId")]
    public Guid Id { get; set; }

    public decimal? Amount { get; set; }

    public int? Date { get; set; }

    public decimal? FareTips { get; set; }

    public ICollection<Extra>? Extras { get; set; }


    [ForeignKey(nameof(User))]
    public string? UserId { get; set; }

    public User? User { get; set; }


}

Extra

public class Extra
{
    [Column("ExtraId")]
    public Guid Id { get; set; }

    [Required(ErrorMessage = "Name is a required field.")]
    public string? Name { get; set; }


    [Required(ErrorMessage = "Amount is a required field.")]
    public decimal? Amount { get; set; }
    
    [ForeignKey(nameof(Fare))]
    public Guid FareId { get; set; }

    public Fare? Fare { get; set; }

    [ForeignKey(nameof(User))]
    public string? UserId { get; set; }

    public User? User { get; set; }

}

你应该看看 how to configure the model to auto-include navigation properties。模型生成器上有一个 AutoInclude 方法可以自动为您执行此操作。

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Fare>().Navigation(f => f.Extras).AutoInclude();
}