In a table I have a list of documents:
public class Document
{
public int Id {get;set;}
public string Slug {get;set;}
public string Name {get;set;}
public string LanguageId {get;set;}
}
The table can have multiple documents with the same 'Slug', but with different 'LanguageId's.
I fetch the data like this:
public async Task<List<T>> GetDocuments<T>(string languageId)
{
var documents = await _dbContext.Documents
.OrderByDescending(x => x.LanguageId == languageId)
.ThenByDescending(x => x.LanguageId == "da")
.ThenBy(x => x.Name)
.AsNoTracking()
.ProjectToType<T>()
.ToListAsync();
return documents;
}
The goal is to only get one document per 'Slug'. If it exists with the submitted 'languageId', that's what I want - if not, I want the one with LanguageId = "da".
It must be a GroupBy, but I can't get the desired result. My current approach is this:
public async Task<List<T>> GetDocuments<T>(string languageId)
{
var documents = await _dbContext.Documents
.OrderByDescending(y => y.LanguageId == languageId)
.ThenByDescending(y => y.LanguageId == "da")
.ThenBy(y => y.Name)
.GroupBy(x => x.Slug)
.Select(x => x.First())
.AsNoTracking()
.ProjectToType<T>()
.ToListAsync();
return documents;
}
But that gives me all documents in the table.
Please help.