使用Linq to Entities </user>返回列表<user>

时间:2013-08-02 08:59:14

标签: c# entity-framework linq-to-entities

我正在开发一个使用Entity Framework 4.4连接到数据库的WCF Rest服务。

我有这个方法:

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

    }
}

我不知道如何从数据库中检索所有List<User>来返回User

我必须这样做吗?

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;
}

或者,有最快的方法吗?

6 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:0)

你应该可以这样做:

public List<User> GetAllUsers()
{

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

        return users.ToList();
    }

}

答案 2 :(得分:0)

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


        return users 
    }
}

答案 3 :(得分:0)

可能就像这样:

return context.Users.ToList();

答案 4 :(得分:0)

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

答案 5 :(得分:0)

这个没问题

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