1

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?

1
  • it depends of how you dbcontext class is called, just right click in your controllers folder then new controller, and use the entitframework template, it will ask you for your dbcontext class (is the one that have your datasets) and for a model in this case User, see that code there is the anwer Commented Apr 24, 2014 at 22:59

2 Answers 2

2

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();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.