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:
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
.
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
});