Search code examples
c#linqentity-framework-core

C# EF Core Select Specific Column via Condition


I have a Table in the Database which has around 100+ columns.

I have a query which will select specific columns from a Database. But I want to do in a dynamic way. From the 100+ columns 2 Columns will always be there and there will be one more column from the 100+ column.

For now I am using a Select Expression

Expression<Fun<MyTable,MyDto>> Select = p => new MyDto() {
 Column1 = p.Column1,
 Column2 = p.Column2,
 Extra = p.(on of the 100 Column)
}

But I want to set this Extra Property to one of the column dynamically.

Something like

if (SomeCondition) // This  can an Enum or a String which will determine which column to chose
{

 Select.Extra = (one of the 100 Column)
}
else {
 Select.Extra = (one of the 100 Column)

}

Is there a way to update the selected columns on Runtime?


Solution

  • So I was able to figure things out based on the comment of smoksnes.

    First use this Library:

    using System.Linq.Dynamic.Core;
    

    But I want to share the solution I made up plus what I chose over the other

    My Solution:

    Expression<Fun<MyTable,MyDto> Select = p => new MyDto() {
       Column1 = p.Column1,
       Column2 = p.Column2,
      Extra = p.GetType().GetProperty("ColumnNameToSelect").GetValue(p).ToString()
    }
    

    Now the above solution works but performance wise it sucks when going for large numbers of rows 10000+ as compared to the solution below.

    Solution I went with

    _context.MyTable.Where(p => p.IsDeleted == false)
    .Select<MyDto>($"new (Column1 as Column1,Column2 as Column2, Extra as {"ColumnNameToSelect"})")
    .ToList()
    

    The above solution has better performance so go with that and only go with the first if that satisfies you use case.

    These both solution work with EF Core and this is Tested on NET 6. Don't know about other Versions.