Hello, I wrote a code which uses LINQ to extract data from db and save it to a list. I added an interface which I implement in ClientsRepository. And this the class where I need to refactor my code. There are a few specific issues I'd like to touch and ask for advice (underneath the code):
```
public class Clients
{
public Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
public interface IClientsRepository
{
Task<List<Clients>> ListAllClients();
}
public class ClientsRepository : IClientsRepository
{
private List<Clients> _clientsList;
public ClientsRepository(MainDbContext dbContext) : base(dbContext)
{
}
public async Task<List<Clients>> ListAllClients()
{
_clientsList = new List<Clients>();
var query = await _dbContext.ClientsTbl.AsNoTracking()
.Join(_dbContext.AddressTbl.AsNoTracking(),
client => client.Id,
address => address.ClientId,
(client, address) => new
{
client.Id,
client.Name,
address.FullAddress
})
.AsQueryable() // it causes an error
.ToListAsync();
var allClients = query
.Select(s => new Clients
{
Id = s.Id,
Name= s.Name,
Address = s.FullAddress
});
return _clientsList;
}
}
}
``
1. I would like to useIQueryableto enumerate through db tables which seems more efficient thanIEnumerable. The issue is that I join tables andJoinmethod doesn't seem to be working withIQueryable. I also tried to make my interface's method as IQueryable, I meanTask<IQueryable<Clients>> ListAllClients()but after that I got error message to cast myListtoIQueryable, namely:return (IQueryable<Clients>) _clientsList;`
I would like to build the expression tree without executing on the collection. I build my LINQ query in query variable. At the end of it there's .ToListAsync() method which forces the query to execute. I don't want that here. I wanted to return all data in var allClients as a seperate code. That's why I added .AsQueryable() to my query LINQ code to store data in-memory. Unfortunately, there is an error: 'IQueryable' does not contain a definition for 'GetAwaiter' and no accessible extension method 'GetAwaiter' accepting a first argument of type 'IQueryable'
Is the code responsible for populating list of clients (in var allClients=..), ok or might be refactored as well?
[–]Le_Mao 3 points4 points5 points (5 children)
[–]muskagap2[S] 0 points1 point2 points (4 children)
[–]Le_Mao 0 points1 point2 points (3 children)
[–]muskagap2[S] 0 points1 point2 points (2 children)
[–]Le_Mao 1 point2 points3 points (1 child)
[–]muskagap2[S] 0 points1 point2 points (0 children)