I am developing an MVC application using Entity Framework. I want to get 5 columns from a table and return them in an IEnumerable type. My code for this is:
First you don't need the ToList()
because you don't need a list:
db.MSTs
.Select(x => new { x.Id, x.Code, x.Desc, x.L1, x.L2 })
.OrderBy(h => h.Code)
Now you do need the type to be MST
. If this was a type EF knew about you could include this directly in the Select
:
db.MSTs
.Select(x => new MST{ Id = x.Id, Code =x.Code, Desc = x.Desc, L1 =x.L1, L2 =x.L2 })
.OrderBy(h => h.Code)
But it's not, so you need to break from EF to in-memory with AsEnumerable
and then do the creation of MST
after that:
IEnumerable<MST> n = db.MSTs
.Select(x => new { x.Id, x.Code, x.Desc, x.L1, x.L2 }).OrderBy(h => h.Code)
.AsEnumerable()
.Select(x => new MST{ Id = x.Id, Code =x.Code, Desc = x.Desc, L1 =x.L1, L2 =x.L2 });
(If there's some reason why you really do need the ToList()
you can use that instead of AsEnumerable()
, but you're probably better off just placing a final ToList()
after all of that, to get a list of the type you actually want).
If you were using asynchronous code, then we would similarly place it after the await:
IEnumerable<MST> n = (await db.MSTs
.Select(x => new { x.Id, x.Code, x.Desc, x.L1, x.L2 })
.OrderBy(h => h.Code)
.ToListAsync())
.Select(x => new MST{ Id = x.Id, Code =x.Code, Desc = x.Desc, L1 =x.L1, L2 =x.L2 });
You need to simply project the Type MST
instead of anonymous type:-
n = db.MSTs.Select(x => new MST
{
Id = x.Id,
Code = x.Code,
Desc = x.Desc,
L1= x.L1,
L2 = x.L2
}).OrderBy(h => h.Code);
Provided, you have all these properties in MST
. Also, it should not be a mapped entity it should be a DTO.
Also, you don't need ToList
here since Select
returns IEnumerable<T>
.
Update:
Since it is a mapped entity in Entity Framework, one way is to first project the anonymous type and then the Model type like this:-
n = db.MSTs.Select(x => new
{
x.Id,
x.Code,
x.Desc,
x.L1,
x.L2
}).OrderBy(h => h.Code)
.AsEnumerable()
Select(x => new MST
{
Id = x.Id,
Code = x.Code,
Desc = x.Desc,
L1= x.L1,
L2 = x.L2
});