With recent versions of EF Core selecting into KeyValuePair appears to work fine. I also verified that (on MS SQL Server) the SQL only selects the two relevant fields, so the "Select" is actually translated:
return context.myTable
.Select(x => new KeyValuePair<int, string>(o.columnA, o.columnB))
.ToList();
SELECT [m].[columnA], [m].[columnB]
FROM [myTable] AS [m]
The generated SQL is the same as for anonymous classes, except that renames are only made for the latter (e.g. "AS A"):
return context.myTable
.Select(x => new {A = o.columnA, B = o.columnB})
.ToList();
SELECT [m].[columnA] AS [A], [m].[columnB] AS [B]
FROM [myTable] AS [m]
Tested with .NET 6.
Note that using a Dictionary (as suggested in other answers) will introduce additional constraints compared to a List of KeyValuePairs:
- The order of Dictionary entries is undefined. Thus, while one (currently) typically has the same order of elements for filling in and enumerating over a Dictionary, this is not guaranteed (I've already seen cases of reordering) and might change without notice in the future.
- The key values in a Dictionary must be unique (which may or may not apply to columnA in the database, and would cause an exception if columnA is not).
- Dictionary does not allow "null" for the key (This is just for completeness, since the OP uses "int" type for the key anyway).
- The Dictionary keeps an index of its keys, so setting it up might take longer than just having a list of KeyValuePairs (though this is micro-optimisation ...)
Depending on the use case of the OP (which I cannot deduce from the question), some of these constraints might be desirable, though, and the Dictionary might actually be the solution.