I have a Repository base class like so:
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);
}
}
This is working fine to retrieve a single entity. But how can I modify it to retrieve its navigational properties too?
I saw this kind of answer here on Stackoverflow. But I do not know how to apply it to my base class above. Any help, please.
RepositoryContext.Model.GetEntityTypes()
.Select(t => new
{
t.ClrType.Name,
NavigationProperties = t.GetNavigations()
.Select(x => x.PropertyInfo)
});
My query is like so:
public async Task<IEnumerable<Fare>>
GetAllFaresByUserAsync(string userId, bool trackChanges)
{
return await FindByCondition(e => e.UserId.Equals(userId),
trackChanges).ToListAsync();
}
The models are like so: I can get the Fares
collection using my query above. But "extras": [],
is the problem here?
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; }
}
CodePudding user response:
You should have a look at how to configure the model to auto-include navigation properties. There's an AutoInclude
method on the model builder that does this for you automatically.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Fare>().Navigation(f => f.Extras).AutoInclude();
}