I\'m building a Web API project that will be made available to third-party\'s and also used by my own web application/s. The Web API methods will return JSON representations
The complete method could be:
public List<User> Get()
{
using (var db = new MyContext())
{
return (from u in db.Users
orderby u.FirstName
select new User()
{
Id = u.pkUser,
Username = u.Username,
Password = u.Password,
Active = u.Active
}).ToList();
}
}
You said you want the result "without iteration". Using LINQ also does not eliminate the iteration. You are not doing it in your code, but it really happens when you call the ToList()
method.
You can use LINQ to Objects to do the conversion:
using (var db = new MyContext())
{
var query = from u in db.Users
orderby u.FirstName
select u;
return query.AsEnumerable().Select(item =>
new User
{
Id = item.pkUser,
Username = item.Username,
Password = item.Password,
Active = item.Active
}).ToList();
}
We can get really compact if we use AutoMapper.
Bootstrap the mapper in your repository:
Mapper.CreateMap<AutoGenNamespace.User, DtoNamespace.User>();
Then it's pretty simple (and there's nothing wrong with returning IEnumerable).
public IEnumerable<User> Get()
{
using (var db = new MyContext())
{
return (from u in db.Users
orderby u.FirstName
select Mapper.Map(u)).AsEnumerable();
}
}
In my query I have parent table with multiple childs.
public class TeamWithMembers
{
public int TeamId { get; set; }
public string TeamName { get; set; }
public string TeamDescription { get; set; }
public List<TeamMembers> TeamMembers { get; set; }
}
In this when I was using the ToList()
in the linq query it is giving the error.
Now I am using the anonymous type in the linq query and convert it into the next query like this
List<TeamModel.TeamWithMembers> teamMemberList = teamMemberQueryResult.AsEnumerable().Select(item =>
new TeamModel.TeamWithMembers() {
TeamId=item.TeamId,
TeamName=item.TeamName,
TeamMembers=item.TeamMembers.ToList()
}).ToList();
Where teamMemberQueryResult
is the resultset from the linq query.