I want to select the multiple column based on if condition, While adding "Select" method as nested it is not working, Getting null for each properties in the class. So how to fix this?
public async Task<Form?> GetFormByIdAsync(long formId, string organisationId,
bool includeBuilderSchema = false,bool includeViewerSchema = false)
{
var query = _dbContext.Forms.AsQueryable()
.Where(f => f.Id.Equals(formId) && f.OrganizationId.Equals(organisationId)).Select(f =>
new Form()
{
Id = f.Id,
Name = f.Name,
Description = f.Description,
});
if (includeBuilderSchema)
{
query = query.Select(f => new Form()
{
FormBuilderSchema = f.FormBuilderSchema,
});
}
if (includeViewerSchema)
{
query = query.Select(f => new Form()
{
FormViewerSchema = f.FormViewerSchema,
});
}
var result = await query
.FirstOrDefaultAsync();
return result;
}
2
Answers
I added condition using ternary operator while assigning fields inside Select function.
When
includeBuilderSchema
is true, thegeneratedQuery
is changed correctly.But not sure is it good coding practice.
The second SELECT is overriding the first, only the FormBuilderSchema and OrganizationId props are initialized. Try: