1

Ok So I am just simply needing good instructional pages on how to design a Class for retrieving data from the database. I can find information all over on how to take an existing database and create an Entity Framework from it but I am trying to do code first.

I am able to insert Data (although I am not 100% sure how that is working) I just cannot seem to figure out how to pull the data from the database using the class(Model) that is created and display that data on a Razor page.

I have no problem with doing the studying and learning this but I am having a terrible time at finding good information that will just do a true walk through of this process.

Once again I am not looking for the Entity Framework.

Thank you for all of the help you can provide.

1

1 Answer 1

2

There is a lot of tutorials out there in the internet. Here is a small example to pull your data from table and show in the view.

Assuming you have a model class called User like this

public class User
{
  public int ID { set;get;}
  public string FirstName { set;get;}
}

Add properties like this to your DataContext class for each of your model entities. The property is of type DbSet.

public class YourDataContext: DbContext
{
  public DbSet<User> Users {set;get;}  
}

Then in your controller action method, you can create an instance of your DBContext class and access its Users property. Pass that to our view.

public class UserController : Controller
{
  public ActionResult Index()
  {
    YourDBContext db=new YourDBContext();
    var users=db.Users.ToList();
    return View(users)
  }
}

Have an index.cshtml view like this under Views/User folder.

@model IEnumerable User

@foreach(var user in Model)
{
   <p>@user.FirstName</p>
}
Sign up to request clarification or add additional context in comments.

1 Comment

darn I want to click the check on both of these due to both are on point and answered my question.

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.