Understanding how to load and retrieve information from a database using a controller using ASP.NET.

I am currently working on a project where I need to retrieve data from a database and order and sort it. Examining the Generated Code: https://learn.microsoft.com/en-us/aspnet/mvc/overview/getting-started/introduction/accessing-your-models-data-from-a-controller I have never done this before. And I have been advised to look at the documentation tutorial. Upon reviewing it I fail to understand the process. Is Moviecontext a super object that we pass properties and abilities to it through inheritance and value assignment? Do we use properties to assign capabilities? And than also how is the information passed to the view and ordered? Do we use DbSet<Entity> properties to add capabilites to the object we are trying to pass to the view? DbContext options configure the DdbBontext object. Textbook example
using Microsoft.EntityFrameworkCore;

namespace MovieList.Models {
public class MovieContext : DbContext
{
public MovieContext(DbContextOptions<MovieContext> options)
: base(options)
{ }
public DbSet<Movie> Movies { get; set; } = null!;
}
}

using Microsoft.EntityFrameworkCore;

namespace MovieList.Models {
public class MovieContext : DbContext
{
public MovieContext(DbContextOptions<MovieContext> options)
: base(options)
{ }
public DbSet<Movie> Movies { get; set; } = null!;
}
}

in this example its not loading anything.
Accessing Your Model's Data from a New Controller
In this section, you'll create a new MoviesController class and write code that retrieves the movie data and displays it in the browser using a view template.
39 Replies
Angius
Angius3w ago
Yes, you use DbSets to access data. Think of them as a representation of tables Not sure what you mean by "capabilities" here
strikeouts27
strikeouts27OP3w ago
After reviewing the textbook I believe these are the methods for learning how to search the database for information. Three ways to select a movie by its id int id = 1; var movie = context.Movies.Where(m => m.MovieId == id).FirstOrDefault(); var movie = context.Movies.FirstOrDefault(m => m.MovieId == id); var movie = context.Movies.Find(id);
// Code that builds a query expression
IQueryable<Movie> query = context.Movies.OrderBy(m => m.Name);

// Code that executes a query expression List<Movie> movies = query.ToList();
Code that builds and executes a query expression
var movies = context.Movies.OrderBy(m => m.Name).ToList();

//Code that builds a query expression by chaining LINQ methods
var query = context.Movies.Where(m => m.Rating > 3).OrderBy(m => m.Name);

// Code that builds a query expression on multiple lines
IQueryable<Movie> query = context.Movies; query = query.Where(m => m.Year > 1970); query = query.Where(m => m.Rating > 3); query = query.OrderBy(m => m.Name);
//Three ways to select a movie by its id
int id = 1;
var movie = context.Movies.Where(m => m.MovieId == id).FirstOrDefault();
var movie = context.Movies.FirstOrDefault(m => m.MovieId == id);
var movie = context.Movies.Find(id);
// Code that builds a query expression
IQueryable<Movie> query = context.Movies.OrderBy(m => m.Name);

// Code that executes a query expression List<Movie> movies = query.ToList();
Code that builds and executes a query expression
var movies = context.Movies.OrderBy(m => m.Name).ToList();

//Code that builds a query expression by chaining LINQ methods
var query = context.Movies.Where(m => m.Rating > 3).OrderBy(m => m.Name);

// Code that builds a query expression on multiple lines
IQueryable<Movie> query = context.Movies; query = query.Where(m => m.Year > 1970); query = query.Where(m => m.Rating > 3); query = query.OrderBy(m => m.Name);
//Three ways to select a movie by its id
int id = 1;
var movie = context.Movies.Where(m => m.MovieId == id).FirstOrDefault();
var movie = context.Movies.FirstOrDefault(m => m.MovieId == id);
var movie = context.Movies.Find(id);
Angius
Angius3w ago
All correct, yes
strikeouts27
strikeouts27OP3w ago
According to the textbook configuration options powers are given to this object like the ability to restrict txt length and other database restrictions
Angius
Angius3w ago
Yes, you can configure how those tables end up generated
strikeouts27
strikeouts27OP3w ago
Okay so I I want to access the database and grab information from it I create an object called context Thats where we make it possible to create an object that has DbContext abilities Ill do this step by step.
// A MovieContext class that inherits the DbContext class
using Microsoft.EntityFrameworkCore;
namespace MovieList.Models {
public class MovieContext : DbContext
// A MovieContext class that inherits the DbContext class
using Microsoft.EntityFrameworkCore;
namespace MovieList.Models {
public class MovieContext : DbContext
Thats where we make it possible to create an object that has DbContext abilities Here is where we pass configuration objects.
public MovieContext(DbContextOptions<MovieContext> options) : base(options)
{ }
public MovieContext(DbContextOptions<MovieContext> options) : base(options)
{ }
So is there were we say load up the movies database table in its entirety or just the column.
public DbSet<Movie> Movies { get; set; } = null!;
public DbSet<Movie> Movies { get; set; } = null!;
Angius
Angius3w ago
Neither is loaded here The DbContext just describes the database, and DbSets the tables Nothing is loaded until you explicitly load it
strikeouts27
strikeouts27OP3w ago
okay how do i actually do that
Angius
Angius3w ago
like this, for example
strikeouts27
strikeouts27OP3w ago
um were you going to show an example?
Angius
Angius3w ago
It's in the message I replied to
strikeouts27
strikeouts27OP3w ago
all I am seeing is like this, for example
Angius
Angius3w ago
But, sure
var movies = context.Movies // nothing loaded
.OrderBy(m => m.Title) // nothing loaded
.Where(m => b.ReleaseYear > 1999) // nothing loaded
.Select(m => m.Genre) // nothing loaded
.ToList(); // NOW the query gets executed and the results loaded!
var movies = context.Movies // nothing loaded
.OrderBy(m => m.Title) // nothing loaded
.Where(m => b.ReleaseYear > 1999) // nothing loaded
.Select(m => m.Genre) // nothing loaded
.ToList(); // NOW the query gets executed and the results loaded!
Angius
Angius3w ago
No linked message above?
No description
strikeouts27
strikeouts27OP3w ago
oh wow! NO Wonder I was confused! I see this part So basically there is a series of instructions for what data needs to be organized and how, and than .ToList(); executes the command to actually grab the data!
Angius
Angius3w ago
.ToList() among others, yes .First(), .Count(), .FirstOrDefault(), and probably a few others also do that Generally, whatever method does not return an IQueryable<T> probably resolves the query
strikeouts27
strikeouts27OP3w ago
typing one sec
// A MovieContext class that inherits the DbContext class
using Microsoft.EntityFrameworkCore;
{
namespace MovieList.Models
{
public class MovieContext : DbContext
{
public MovieContext(DbContextOptions<MovieContext> options)
: base(options)
{ }
public DbSet<Movie> Movies { get; set; } = null!;
}
}
// A MovieContext class that inherits the DbContext class
using Microsoft.EntityFrameworkCore;
{
namespace MovieList.Models
{
public class MovieContext : DbContext
{
public MovieContext(DbContextOptions<MovieContext> options)
: base(options)
{ }
public DbSet<Movie> Movies { get; set; } = null!;
}
}
So we take the time to create a class called Movie Context. and dpass it DbContext abilities and DbContexOptions And than.... where does the context keyword get involved?
Angius
Angius3w ago
What do you mean by "context keyword"?
strikeouts27
strikeouts27OP3w ago
In your example we assign it these powers?
var movies = context.Movies // nothing loaded
.OrderBy(m => m.Title) // nothing loaded
.Where(m => b.ReleaseYear > 1999) // nothing loaded
.Select(m => m.Genre) // nothing loaded
.ToList(); // NOW the query gets executed and the results loaded!
var movies = context.Movies // nothing loaded
.OrderBy(m => m.Title) // nothing loaded
.Where(m => b.ReleaseYear > 1999) // nothing loaded
.Select(m => m.Genre) // nothing loaded
.ToList(); // NOW the query gets executed and the results loaded!
Angius
Angius3w ago
You could call it many things, but not "assigning powers" lmao
strikeouts27
strikeouts27OP3w ago
but the keyword context comes from no where. There is no class that instatnated it
Angius
Angius3w ago
Ah, so you're asking about dependency injection then
strikeouts27
strikeouts27OP3w ago
Yes that word keeps getting thrown around.
Angius
Angius3w ago
For all intents and purposes, all you need to know that it's a magic box of stuff, and anything in that box can access anything else in that box So if you have two classes registered in a DI container, say
builder.Services.AddTransient<Foo>();
builder.Services.AddTransient<Bar>();
builder.Services.AddTransient<Foo>();
builder.Services.AddTransient<Bar>();
you can use the constructor to tell Bar to grab Foo from the box:
public class Bar
{
private readonly Foo _foo;

public Bar(Foo foo)
{
_foo = foo;
}
}
public class Bar
{
private readonly Foo _foo;

public Bar(Foo foo)
{
_foo = foo;
}
}
The DI container will create an instance of Foo And just pass it to Bar
strikeouts27
strikeouts27OP3w ago
my textbook shows me this
// A connection string in the appsettings.json file
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},

"AllowedHosts": "*",
"ConnectionStrings": {
"MovieContext": "Server=(localdb)\\mssqllocaldb;Database=Movies; Trusted_Connection=True;MultipleActiveResultSets=true"
} }

// Code that enables dependency injection for DbContext objects
using Microsoft.EntityFrameworkCore;
using MovieList.Models;

var builder = WebApplication.CreateBuilder(args);
// Add services to the container. builder.Services.AddControllersWithViews(); // Add EF Core DI
builder.Services.AddDbContext<MovieContext>(options =>
options.UseSqlServer(
builder.Configuration.GetConnectionString("MovieContext")));
var app = builder.Build();
// A connection string in the appsettings.json file
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},

"AllowedHosts": "*",
"ConnectionStrings": {
"MovieContext": "Server=(localdb)\\mssqllocaldb;Database=Movies; Trusted_Connection=True;MultipleActiveResultSets=true"
} }

// Code that enables dependency injection for DbContext objects
using Microsoft.EntityFrameworkCore;
using MovieList.Models;

var builder = WebApplication.CreateBuilder(args);
// Add services to the container. builder.Services.AddControllersWithViews(); // Add EF Core DI
builder.Services.AddDbContext<MovieContext>(options =>
options.UseSqlServer(
builder.Configuration.GetConnectionString("MovieContext")));
var app = builder.Build();
Angius
Angius3w ago
builder.Services.AddDbContext<MovieContext>()
builder.Services.AddDbContext<MovieContext>()
is what adds your MovieContext into the DI box Then, sometime later, you should have something like .AddMvc() or .AddRazorPages() or something like that That's what adds your controllers to the box So now, the controllers can tell the box to give them the context
strikeouts27
strikeouts27OP3w ago
So the DI container creates an object named Foo. And than the class of Bar creates an ojbect named Bar but when it does, it grabs the created Foo object and gains its methods an attributes.
builder.Services.AddTransient<Foo>();
builder.Services.AddTransient<Bar>();

you can use the constructor to tell Bar to grab Foo from the box:
public class Bar
{
private readonly Foo _foo;

public Bar(Foo foo)
{
_foo = foo;
}
}
builder.Services.AddTransient<Foo>();
builder.Services.AddTransient<Bar>();

you can use the constructor to tell Bar to grab Foo from the box:
public class Bar
{
private readonly Foo _foo;

public Bar(Foo foo)
{
_foo = foo;
}
}
Angius
Angius3w ago
The Bar class is also managed by the DI container But yes, that's basically it
strikeouts27
strikeouts27OP3w ago
Can you explain the DI container? what is that? I know I am asking a lot of questions thank you for your patience.
Angius
Angius3w ago
The magic box of stuff Really, it's easier when you just think about it as such
strikeouts27
strikeouts27OP3w ago
So depdency injection, put simply is when the DI creates an object that another class will use when creating its objects.
Angius
Angius3w ago
Yep
strikeouts27
strikeouts27OP3w ago
So where was context born? Do you offer tutoring services in C# you seem to know your stuff.
Angius
Angius3w ago
The DI container instantiated it And no, I don't do private tutoring
strikeouts27
strikeouts27OP3w ago
darnit okay so I need to learn about the DI container from the documentation. see how it created context. context can than as a super object grab all of the infomration in a database table and than we use LINQ methods to retrieve information from that object. man my textbook is worthless. okay i need to research that. @Angius thank you I will look into this and than try to access data. If I have more questions i should just keep asking them here correct?
Angius
Angius3w ago
Generally, DI is simply nothing you worry about You just put things in the box, and request them from the box
strikeouts27
strikeouts27OP3w ago
var movies = context.Movies // nothing loaded
.OrderBy(m => m.Title) // nothing loaded
.Where(m => b.ReleaseYear > 1999) // nothing loaded
.Select(m => m.Genre) // nothing loaded
.ToList(); // NOW the query gets executed and the results loaded!
var movies = context.Movies // nothing loaded
.OrderBy(m => m.Title) // nothing loaded
.Where(m => b.ReleaseYear > 1999) // nothing loaded
.Select(m => m.Genre) // nothing loaded
.ToList(); // NOW the query gets executed and the results loaded!
this would be pulling things from the box. @Angius I cannot thank you enough all of this has been a challenge for me. I am trying my best to become a programmer and escape customer service.
Angius
Angius3w ago
:Ok:
Unknown User
Unknown User3w ago
Message Not Public
Sign In & Join Server To View

Did you find this page helpful?