How can I convert Linq results to DTO class object without iteration

.net c# entity-framework linq


I'm creating a Web API project that will be used by my own web applications as well as those of third parties. Complex types and objects will be represented in JSON by the Web API functions. These are pre-defined classes that I can make available to third parties so they can deserialize the JSON and comprehend how the data is arranged. Until I hear otherwise, I'll refer to these classes as DTO classes.

I have the User class with a relationship to the Scan table in the following automatically produced entity model (from database) (relationship can be ignored for the purpose of this question)...

public partial class User
    public User()
        this.Scans = new HashSet<Scan>();

    public int Id { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    public bool Active { get; set; }

    public virtual ICollection<Scan> Scans { get; set; }

Additionally, I would like to return the following DTO class as a List to the presentation layer (I don't believe I should use IEnumerable for business to presentation?).

public class User
    public int Id;
    public string Username;
    public string Password;
    public bool Active;

For this component, my business layer currently looks like what is shown below. obtaining people from the database using Linq, parsing the outcomes, and then returning a List of POCO Users.

public List<User> Get()
    List<User> userList = new List<User>();

    using (var db = new MyContext())
        var query = from u in db.Users
                    orderby u.FirstName
                    select u;

        foreach (var item in query)
            User user = new User();
            user.Id = item.pkUser;
            user.Username = item.Username;
            user.Password = item.Password;
            user.Active = item.Active;


    return userList;

It seems inefficient to parse through the results in this manner, but I've observed that you can accomplish this with a Linq query without iteration (e.g. the answer in this question mapping the results of a Linq Query to a DTO class).

To enable this kind of Linq query on my objects, I'm not sure where or how to implement IEnumerable. I'm also not sure how to build a query similar to the one in the referenced question above but for my much simpler scenario.

Any assistance is greatly appreciated.

P.S. Please disregard the fact that I am returning all Users at once and that I am exposing Username and Password via Web API. For the sake of answering your question, I've condensed my code into the example above.

5/23/2017 12:34:39 PM

Accepted Answer

2/28/2013 12:07:18 AM

Popular Answer


Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow