VansFannel
VansFannel

Reputation: 45921

Return List<User> using Linq to Entities

I'm developing a WCF Rest service that connect to a database using Entity Framework 4.4.

I have this method:

public List<User> GetAllUsers()
{
    using (var context = new AdnLineContext())
    {
        var users = from u in context.Users
                    select u;

    }
}

And I don't know how to return a List<User> with all Users retrieved from database.

Do I have to do this?

public List<User> GetAllUsers()
{
    List<User> usersList = null;

    using (var context = new AdnLineContext())
    {
        var users = from u in context.Users
                    select u;

        usersList = new List<User>();
        foreach (User user in users)
            usersList.Add(user);
    }

    return usersList;
}

Or, is there a fastest way to do it?

Upvotes: 1

Views: 860

Answers (6)

Taj
Taj

Reputation: 1728

public List<User> GetAllUsers()
{
    using (var context = new AdnLineContext())
    {
        var users = (from u in context.Users
                    select u).Tolist();


        return users 
    }
}

Upvotes: 0

Ajay
Ajay

Reputation: 6590

This one is ok

public List<User> GetAllUsers()
{
    using(var context = new AdnLineContext())
    {
     var users = (from u in context.Users
                  select u).ToList();
     return users;
    }
}

Upvotes: 0

Lotok
Lotok

Reputation: 4607

using (var context = new AdnLineContext())
{    
  return context.Users.Select(u=>u).ToList();  
}

Upvotes: 0

Dmytro
Dmytro

Reputation: 1600

Probably, like this:

return context.Users.ToList();

Upvotes: 0

DerApe
DerApe

Reputation: 3175

You should be able to do this:

public List<User> GetAllUsers()
{

    using (var context = new AdnLineContext())
    {
        var users = from u in context.Users
                    select u;

        return users.ToList();
    }

}

Upvotes: 0

Giannis Paraskevopoulos
Giannis Paraskevopoulos

Reputation: 18411

var users = from u in context.Users
                    select u;
return users.ToList();

Upvotes: 3

Related Questions