简体   繁体   中英

How to query list using Entity framework

I am new to Entity framework.

I am working with Entity framework Code First, and created 4 classes.

The Schema is:

  • Many users <-> Many Roles
  • one User <-> Many Post
  • Many Post <-> Many Tag

I have an area of Admin, and a controller called UsersController, with an ActionResult of returning a view.

public ActionResult Index()
{
   return View();
}

I created a strongly typed view from ViewModels. In my viewmodels, I created a class with:

public class UsersIndex 
{
   public IEnumerable<User> Users { get; set; }
}

For my view, I've seen some code examples where the view can have a foreach loop:

@MyBlog.Areas.Admin.ViewModel
<tbody>
    @foreach (var user in Model.Users)
    {
        <tr>
            <td>@user.Id</td>
            <td>@user.Username</td>
            <td>@user.Email</td>
        </tr>
    }
</tbody>

But in my controller, how can I grab the users from my database to pass to my viewmodels into my view?

You need to hydrate your viewmodel using the EF context.

public ActionResult Index()
{
    var model =
        new UsersIndex
        {
            Users = GetUsers()
        };

   return View(model);
}

private IEnumerable<User> GetUsers()
{
    using(var context = new CustomContext())
    {
        return context.Users.ToList();
    }
}

Alternatively if you prefer query syntax.

private IEnumerable<User> GetUsers()
{
    using(var context = new CustomContext())
    {
        return (from user in context.Users
                select user).ToList();
    }
}

One approach would rely on calls from the controller to a repository or a datacontext, or some kind of datahelper class.

In there, you might have something like

public IEnumerable<User> UserReadAll()
{
 using (myEntities _db = new myEntities)
   { 
       return _db.Users.ToList();
   }
}

And in the controller

Public ActionResult MyPage()
{
     var myUserList = MyHelper.UserReadAll();
     return View(myUserList);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM