✅ Understanding how to build controllers.

My controller is supposed to pass ifnormation from the model to the view. My instructor left some code for me to understand. I also wrote out his comments. Can someone help me explain these parts to me?
// Question 1 So the first thing that we do is connect the model to the controller correct? Is that what is happening on this line of code?
// Question 2 I am lost on what context is. Based on my googling this is objects that
// Question 3
//Question 4 is there a way to see the context data as is before formatting?
// Question 5 Iqueryable what is that?

//ViewBag collects information from the models for the view to access correct?

// HomeController.cs
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using FAQ.Models;
using Microsoft.AspNetCore.Http.Features;
using System.Linq;

namespace FAQ.Controllers;

public class HomeController : Controller
{
// I logger provides logging information for the controller.
private readonly ILogger<HomeController> _logger;

public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}

//ASP.NET IActionResult documentaiton: https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.iactionresult?view=aspnetcore-9.0#definition
// IActionResult provides information to MVC about the type of the HTTP response an action method should return.
public IActionResult Index()
{
return View();
}

public IActionResult Privacy()
{
return View();
}


[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}

// Code Example Provided By Professor

}
// The controller retrives FAQS from the database and applies filtering logic.
// The home controller is responsible for retrieving faq
// The controller is responsible for retrieving FAQ's and applying filtering logic.
// Here is what happens inside of the controller.
// It filters the topics based on the selected topic and category.
// it than passes the data to the view using viewbag.
// the index action retrieves faqs and related topics and categories.
// if a topic is selected, it is filtered with the .where method.
// if the the category is selected than the faqs are further refined using the the .where method.
// The filtred list is passed to the views.

// Question 1 So the first thing that we do is connect the model to the controller correct? Is that what is happening on this line of code?
private FaqsContext context { get; set; }

// Question 2 I am lost on what context is. Based on my googling this is objects that have been created correct?
public HomeController (FaqsContext ctx)
{
context = ctx;
}

// Question 3
//ViewBag conllects information from the models for the view to access correct?
//Question 4 is there a way to see the context data as is before formatting?

ViewBag.Topics = context.Topics.OrderBy(t => t.Name).ToList();
ViewBag.Categories = context.Categories.OrderBy(c => c.Name).ToList();

// Question 5 Iqueryable what is that?
IQueryable<FAQ> faqs = context.FAQs
.Include(f => f.Topic)
.Include(f => f.Category)
.OrderBy(f => f.Question);
if (!string.IsNullOrEmpty(topic))
{
faqs = faqs.Where(f = false.TopicId == topic);
}
if (!string.IsNullOrEmpty(category)) {
faqs = faqs.Where(f => f.CategoryId == category);
}

return View(faqs.ToList());
}
}
// Question 1 So the first thing that we do is connect the model to the controller correct? Is that what is happening on this line of code?
// Question 2 I am lost on what context is. Based on my googling this is objects that
// Question 3
//Question 4 is there a way to see the context data as is before formatting?
// Question 5 Iqueryable what is that?

//ViewBag collects information from the models for the view to access correct?

// HomeController.cs
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using FAQ.Models;
using Microsoft.AspNetCore.Http.Features;
using System.Linq;

namespace FAQ.Controllers;

public class HomeController : Controller
{
// I logger provides logging information for the controller.
private readonly ILogger<HomeController> _logger;

public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}

//ASP.NET IActionResult documentaiton: https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.iactionresult?view=aspnetcore-9.0#definition
// IActionResult provides information to MVC about the type of the HTTP response an action method should return.
public IActionResult Index()
{
return View();
}

public IActionResult Privacy()
{
return View();
}


[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}

// Code Example Provided By Professor

}
// The controller retrives FAQS from the database and applies filtering logic.
// The home controller is responsible for retrieving faq
// The controller is responsible for retrieving FAQ's and applying filtering logic.
// Here is what happens inside of the controller.
// It filters the topics based on the selected topic and category.
// it than passes the data to the view using viewbag.
// the index action retrieves faqs and related topics and categories.
// if a topic is selected, it is filtered with the .where method.
// if the the category is selected than the faqs are further refined using the the .where method.
// The filtred list is passed to the views.

// Question 1 So the first thing that we do is connect the model to the controller correct? Is that what is happening on this line of code?
private FaqsContext context { get; set; }

// Question 2 I am lost on what context is. Based on my googling this is objects that have been created correct?
public HomeController (FaqsContext ctx)
{
context = ctx;
}

// Question 3
//ViewBag conllects information from the models for the view to access correct?
//Question 4 is there a way to see the context data as is before formatting?

ViewBag.Topics = context.Topics.OrderBy(t => t.Name).ToList();
ViewBag.Categories = context.Categories.OrderBy(c => c.Name).ToList();

// Question 5 Iqueryable what is that?
IQueryable<FAQ> faqs = context.FAQs
.Include(f => f.Topic)
.Include(f => f.Category)
.OrderBy(f => f.Question);
if (!string.IsNullOrEmpty(topic))
{
faqs = faqs.Where(f = false.TopicId == topic);
}
if (!string.IsNullOrEmpty(category)) {
faqs = faqs.Where(f => f.CategoryId == category);
}

return View(faqs.ToList());
}
}
64 Replies
Angius
Angius4w ago
$code
MODiX
MODiX4w ago
To post C# code type the following: ```cs // code here ``` Get an example by typing $codegif in chat For longer snippets, use: https://paste.mod.gg/
strikeouts27
strikeouts27OP4w ago
You are correct! My Apologies!
Angius
Angius4w ago
Question 1 So the first thing that we do is connect the model to the controller correct? Is that what is happening on this line of code?
It's just a property. Private one, for some reason
Question 2 I am lost on what context is. Based on my googling this is objects that have been created correct?
Only you can know what it is. But, judging by the name and the usage, it's your DbContext, your way to access the database
ViewBag conllects information from the models for the view to access correct?
It's not a great way to go about passing data to the view, but sure, that's what ViewBag can do. You shouldn't really ever use it, though.
Question 4 is there a way to see the context data as is before formatting?
Look it up in the database?
Question 5 Iqueryable what is that?
It's an interface for collections you can query. Mostly used by EF Core to denote the DbSets that represent tables in your database.
strikeouts27
strikeouts27OP4w ago
Thank you ZZZZ!
strikeouts27
strikeouts27OP4w ago
I am stuck and can use some advice. I am trying to get my models data displayed on the web page. To do that I need the controller to retrieve data from the models. https://github.com/strikeouts27/ASP.NET_DallasCollegesAssignments/tree/main The professor provided me the following code but for some reason it is not working.
public class HomeController : Controller {
private FaqsContext context {get; set; }

public HomeController(FaqsContext ctx) {
context = ctx;
}

public IActionResult Index(string topic, string category) {
ViewBag.Topics = context.TopicsOrderBy(t=> t.Name)/ToList();
ViewBag.Categories = context.Categories.OrderBy(c => c.Name).ToList();

IQueryable<FAQ> faqs = context.FAQs
.Include(f => f.Topic)
.Include(f => f.Category)
.OrderBy f => f.Question);

if (!string.IsNullOrEmpty(topic)) {
faqs = faqs.Where(f=> f.TopicId == topic);
}
return View(faqs.ToList();
if (!string.IsNullOrEmpty(category)) {
faqs= faqs.Where(f => f.CategoryId == category);
}
public class HomeController : Controller {
private FaqsContext context {get; set; }

public HomeController(FaqsContext ctx) {
context = ctx;
}

public IActionResult Index(string topic, string category) {
ViewBag.Topics = context.TopicsOrderBy(t=> t.Name)/ToList();
ViewBag.Categories = context.Categories.OrderBy(c => c.Name).ToList();

IQueryable<FAQ> faqs = context.FAQs
.Include(f => f.Topic)
.Include(f => f.Category)
.OrderBy f => f.Question);

if (!string.IsNullOrEmpty(topic)) {
faqs = faqs.Where(f=> f.TopicId == topic);
}
return View(faqs.ToList();
if (!string.IsNullOrEmpty(category)) {
faqs= faqs.Where(f => f.CategoryId == category);
}
GitHub
GitHub - strikeouts27/ASP.NET_DallasCollegesAssignments
Contribute to strikeouts27/ASP.NET_DallasCollegesAssignments development by creating an account on GitHub.
Angius
Angius4w ago
You have an example of how to do that:
No description
strikeouts27
strikeouts27OP4w ago
IQueryable accesses the FAQ context and than it creates a variable that says that it will hold whatever the context's FAQ's are.
Angius
Angius4w ago
You don't need the intermediate IQueryable step
Thing? thing = await context.Things
.Where(t => t.Id == id)
.FirstOrDefaultAsync();
Thing? thing = await context.Things
.Where(t => t.Id == id)
.FirstOrDefaultAsync();
is perfectly fine
strikeouts27
strikeouts27OP4w ago
This is my very first project in ASP.NET so I am a little inexperienced on how to do this. So basically I need to create a new method that returns this inforation. 1. One would be to create a new method
public IActionResult FAQ(){}
public IActionResult FAQ(){}
2. Step two would be grab the information. The information is in the model so I need to use ASP.NET methods to grab it. The first question i ask myself is where is the data? It is in the model. Next I say what techniques and methods retreive information from the models -> google that question Looking at the instructions I ask myself information do I need to grab? -> I need to grab the questions so that they appear on the page. The questions are stored in the The questions data was migrated to the databse.
// HomeController.cs
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using FAQ.Models;
using Microsoft.AspNetCore.Http.Features;
using System.Linq;

namespace FAQ.Controllers;

public class HomeController : Controller
{
// I logger provides logging information for the controller.
private readonly ILogger<HomeController> _logger;

public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}

//ASP.NET IActionResult documentaiton: https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.iactionresult?view=aspnetcore-9.0#definition
// IActionResult provides information to MVC about the type of the HTTP response an action method should return.
public IActionResult Index()
{
return View();
}

public IActionResult Privacy()
{
return View();
}


[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
ViewBag.Topics = context.Topics.OrderBy(t => t.Name).ToList();
ViewBag.Categories = context.Categories.OrderBy(c => c.Name).ToList();

// IQueryable searches
IQueryable<FAQ> faqs = context.FAQs
.Include(f => f.Topic)
.Include(f => f.Category)
.OrderBy(f => f.Question);
if (!string.IsNullOrEmpty(topic))
{
faqs = faqs.Where(f = false.TopicId == topic);
}
if (!string.IsNullOrEmpty(category)) {
faqs = faqs.Where(f => f.CategoryId == category);
}

return View(faqs.ToList());

// Code Example Provided By Professor
// The controller retrives FAQS from the database and applies filtering logic.
// The home controller is responsible for retrieving faq
// The controller is responsible for retrieving FAQ's and applying filtering logic.
// Here is what happens inside of the controller.
// It filters the topics based on the selected topic and category.
// it than passes the data to the view using viewbag.
// the index action retrieves faqs and related topics and categories.
// if a topic is selected, it is filtered with the .where method.
// if the the category is selected than the faqs are further refined using the the .where method.
// The filtred list is passed to the views.
// HomeController.cs
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using FAQ.Models;
using Microsoft.AspNetCore.Http.Features;
using System.Linq;

namespace FAQ.Controllers;

public class HomeController : Controller
{
// I logger provides logging information for the controller.
private readonly ILogger<HomeController> _logger;

public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}

//ASP.NET IActionResult documentaiton: https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.iactionresult?view=aspnetcore-9.0#definition
// IActionResult provides information to MVC about the type of the HTTP response an action method should return.
public IActionResult Index()
{
return View();
}

public IActionResult Privacy()
{
return View();
}


[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
ViewBag.Topics = context.Topics.OrderBy(t => t.Name).ToList();
ViewBag.Categories = context.Categories.OrderBy(c => c.Name).ToList();

// IQueryable searches
IQueryable<FAQ> faqs = context.FAQs
.Include(f => f.Topic)
.Include(f => f.Category)
.OrderBy(f => f.Question);
if (!string.IsNullOrEmpty(topic))
{
faqs = faqs.Where(f = false.TopicId == topic);
}
if (!string.IsNullOrEmpty(category)) {
faqs = faqs.Where(f => f.CategoryId == category);
}

return View(faqs.ToList());

// Code Example Provided By Professor
// The controller retrives FAQS from the database and applies filtering logic.
// The home controller is responsible for retrieving faq
// The controller is responsible for retrieving FAQ's and applying filtering logic.
// Here is what happens inside of the controller.
// It filters the topics based on the selected topic and category.
// it than passes the data to the view using viewbag.
// the index action retrieves faqs and related topics and categories.
// if a topic is selected, it is filtered with the .where method.
// if the the category is selected than the faqs are further refined using the the .where method.
// The filtred list is passed to the views.
Angius
Angius4w ago
That's correct, yes
strikeouts27
strikeouts27OP4w ago
I think i want to write this new method from scratch.
Angius
Angius4w ago
Go ahead, then You have examples of how they're written Based on that, write the one you want
strikeouts27
strikeouts27OP4w ago
okay so I am believing that the information that the controller needs is in the Data/FAQContext file because that is where I migrated the information. I don't think I can just access the model directly. My question is do we use the Context files that we have written as the source of information for the controller to use or do we access the controllers information from the model directly by importing the class
Angius
Angius4w ago
You use the context to access data in your database, yes The data is described by your models
strikeouts27
strikeouts27OP4w ago
According to my professors code context is a property
public class HomeController : Controller
{
private FAQContext context { get; set; }
public class HomeController : Controller
{
private FAQContext context { get; set; }
// FAQ.CS
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using FAQ.Models;

namespace FAQ.Models
{
public class QuestionAnswer
{
// define data models.
public required int Id {get; set;}
public required string Question {get; set;}
public required string Answer { get; set; }
public required string TopicId { get; set; } = null!;
public Topic Topic { get; set; } = null!;
public required string CategoryId { get; set; } = null!;
public Category Category { get; set; } = null!;
}
}
// FAQ.CS
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using FAQ.Models;

namespace FAQ.Models
{
public class QuestionAnswer
{
// define data models.
public required int Id {get; set;}
public required string Question {get; set;}
public required string Answer { get; set; }
public required string TopicId { get; set; } = null!;
public Topic Topic { get; set; } = null!;
public required string CategoryId { get; set; } = null!;
public Category Category { get; set; } = null!;
}
}
Angius
Angius4w ago
The FAQContext class is your context It's stored in a property for some reason But the property itself is not a context
strikeouts27
strikeouts27OP4w ago
Okay so if i want my home page to display the questions and the answers that are stored in the database I need to see how my professors example and than customize it. I need to: 1. Make a method that will activae when the user clicks on it. -> this will require a function and also a link for the user to make the request. -> view problem not a controller problem. 2. This method must make a container to hold the information so that it can be displayed. 2. Use methods that retrieve the information from the database. -> 3. sort the database into a desirable order.
public class HomeController : Controller {
private FaqsContext context {get; set; }

public HomeController(FaqsContext ctx) {
context = ctx;
}

public IActionResult Index(string topic, string category) {
ViewBag.Topics = context.TopicsOrderBy(t=> t.Name)/ToList();
ViewBag.Categories = context.Categories.OrderBy(c => c.Name).ToList();

IQueryable<FAQ> faqs = context.FAQs
.Include(f => f.Topic)
.Include(f => f.Category)
.OrderBy f => f.Question);

if (!string.IsNullOrEmpty(topic)) {
faqs = faqs.Where(f=> f.TopicId == topic);
}
return View(faqs.ToList();
if (!string.IsNullOrEmpty(category)) {
faqs= faqs.Where(f => f.CategoryId == category);
}
public class HomeController : Controller {
private FaqsContext context {get; set; }

public HomeController(FaqsContext ctx) {
context = ctx;
}

public IActionResult Index(string topic, string category) {
ViewBag.Topics = context.TopicsOrderBy(t=> t.Name)/ToList();
ViewBag.Categories = context.Categories.OrderBy(c => c.Name).ToList();

IQueryable<FAQ> faqs = context.FAQs
.Include(f => f.Topic)
.Include(f => f.Category)
.OrderBy f => f.Question);

if (!string.IsNullOrEmpty(topic)) {
faqs = faqs.Where(f=> f.TopicId == topic);
}
return View(faqs.ToList();
if (!string.IsNullOrEmpty(category)) {
faqs= faqs.Where(f => f.CategoryId == category);
}
Angius
Angius4w ago
Something like this, yes
strikeouts27
strikeouts27OP4w ago
Can you simply explain what IActionResult does? My text book says IACTIONRESULT -> The IActionResult type provides information to MVC about the type of HTTP response an action method should return. The response can be content, like HTML or JSON, or it can be an HTTP status code such as 404 Not Found. But what is it being used for here?
Angius
Angius4w ago
It's the return type of this method. Every method needs some return type All sorts of responses you can return from a controller method implement IActionResult So it lets you return, for example BadRequest or NotFound, just as well as it lets you return the view
strikeouts27
strikeouts27OP4w ago
my C# training says returns or not necessarily held data but they are calculated values returned from functions. I know classes create object types and I know that C# has built in types such as string, bool etc. But when you say that it is a return type there must be a series of return objects that I am not aware of. IN prior assignments i used view and it just returned and transmitted simple information that was stored in the method. Perhaps IActionResult is a containmnet assigner.
Angius
Angius4w ago
No idea what "containment assigner" would be IActionResult is an interface. Full stop.
strikeouts27
strikeouts27OP4w ago
package labeler?
Angius
Angius4w ago
Not a thing either It's just an interface I guess you could say it's a marker interface, that is used on types that are valid to return from a controller method So, sure
strikeouts27
strikeouts27OP4w ago
an interface oo1 I just learned about that in my advanced C# it is a class that cannot create objects. its a class that you use for planning out future classes without actually writing a valid class. -> i thought it was an outline tool or something people would use to instruct others.
Angius
Angius4w ago
It's not a class It's an interface Classes can implement interfaces Interfaces are not classes An interface is a contract, might've heard that one said multiple times
strikeouts27
strikeouts27OP4w ago
Okay! So it seems that it does return different types of results to the browser! IActionResult has different capabilities for different requirements. ViewResult RedirectResult RedidrectToActioNResult JsonResult FileResult StatusCodeResult ContentResult EmptyResult
Angius
Angius4w ago
More precisely, all those classes implement IActionResult But yes
strikeouts27
strikeouts27OP4w ago
So in this case it is returning a view that has informaiton which overrides the default view() which warrents the need for Iaction result. it seems that thsi particular controller method is overwriting the index method. and it is saying if you want this particular method to activate you need to have a topic an a category for the method to activate. I am assuming that these requirements will be met when the user does something on the page.
public IActionResult Index(string topic, string category) {}
public IActionResult Index(string topic, string category) {}
Now for actually grabbing the data. ViewBag.Topics -> the viewbag object will create an attribute name topics as a contiainer on that object. that object will than hold the calculated values that the reterival code will provide. What is going on here? is this where he specifies where the controller must go to gain all information and defines all of that information in a varaible called context?
public HomeController(FaqsContext ctx) {
context = ctx;
}
public HomeController(FaqsContext ctx) {
context = ctx;
}
context
ViewBag.Topics = context.Topics.OrderBy(t=> t.Name).ToList();
ViewBag.Topics = context.Topics.OrderBy(t=> t.Name).ToList();
Angius
Angius4w ago
context.Topics.OrderBy(t=> t.Name).ToList() fetches all topics from the database, sorting them by name Then, it puts those items in the viewbag's Topics property
strikeouts27
strikeouts27OP4w ago
okay perfect so when grabbing columns information from a database this is one way to get it done.
Angius
Angius4w ago
Yeah
strikeouts27
strikeouts27OP4w ago
im on it Next is IQueryable I Queryable says I will go into the database and do a search for inforamiton. In this case, we use this tool when the location is not specified. We have to specify where the data is being held to be searched and than after that search we are allowed to use a variable to hold that infromation. To keep things simply the FAQContext is where the data is stored.
Angius
Angius4w ago
You could say that, yeah
strikeouts27
strikeouts27OP4w ago
Here is where I am hitting a snag. context is not defined in the method. but it is outside of the body.
public HomeController(FAQContext ctx)
{
context = ctx;
}

//ASP.NET IActionResult documentaiton: https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.iactionresult?view=aspnetcore-9.0#definition
// IActionResult provides information to MVC about the type of the HTTP response an action method should return.
public IActionResult Index(string topic, string category)
{
ViewBag.Topics = context.Topics.OrderBy(t => t.Name).ToList();
ViewBag.Categories = context.Categories.OrderBy(c => c.Name).ToList();
return View();

IQueryable<FAQContext> faqs = context.FAQs

}
public HomeController(FAQContext ctx)
{
context = ctx;
}

//ASP.NET IActionResult documentaiton: https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.iactionresult?view=aspnetcore-9.0#definition
// IActionResult provides information to MVC about the type of the HTTP response an action method should return.
public IActionResult Index(string topic, string category)
{
ViewBag.Topics = context.Topics.OrderBy(t => t.Name).ToList();
ViewBag.Categories = context.Categories.OrderBy(c => c.Name).ToList();
return View();

IQueryable<FAQContext> faqs = context.FAQs

}
Cannot implicitly convert type 'Microsoft.EntityFrameworkCore.DbSet<FAQ.Models.QuestionAnswer>' to 'System.Linq.IQueryable<FAQ.Data.FAQContext.FAQContext>'
Angius
Angius4w ago
Correct, a DbSet is not IQueryable You can use .AsQueryable() if you want Or you can just start... querying it With .Where(), .OrderBy() and so on
strikeouts27
strikeouts27OP4w ago
My question would first be, where can I find the storage location of the data? The data specifications are held in the model. And dthan tthe HomeController.cs is where the objects are instantiated and migrated correct? If that is true than I would look at my database and perhaps search for the columns and rows where the data is being stored. and than specifiy it there?
Angius
Angius4w ago
Not sure what you mean here The models describe the data as it is in the database
strikeouts27
strikeouts27OP4w ago
I need to find where the data is stored
Angius
Angius4w ago
In the database Whatever the database you're using might be
strikeouts27
strikeouts27OP4w ago
sql server so do i just open the database and look at the columns and rows?
Angius
Angius4w ago
If you want to, yeah
strikeouts27
strikeouts27OP4w ago
I installed it but I don't know how to open sql server to see the data.
Angius
Angius4w ago
To be perfectly honest, I'm not sure either. I usually use Postgres and connect to it from Rider or some such. So I won't be of much help here
strikeouts27
strikeouts27OP4w ago
i managed to do a select query but its not accepting my databse. so if i do get the query running i would see my database columns and rows how would i tell asp.net to grab the information i need
Angius
Angius4w ago
Did you add any data to the database already? What information, exactly?
strikeouts27
strikeouts27OP4w ago
FAQContext.cs
FAQContext.cs
Angius
Angius4w ago
Did you create and apply migrations?
strikeouts27
strikeouts27OP4w ago
I did transmit seed data for this project. yes i ran one migration.
Angius
Angius4w ago
Both Add-Migration and Update-Database?
strikeouts27
strikeouts27OP4w ago
Yes I did
Angius
Angius4w ago
Everything should be fine, then. What doesn't work?
strikeouts27
strikeouts27OP4w ago
Cannot implicitly convert type 'Microsoft.EntityFrameworkCore.DbSet<FAQ.Models.QuestionAnswer>' to 'System.Linq.IQueryable<FAQ.Data.FAQContext.FAQContext>'. An explicit conversion exists (are you missing a cast?)CS0266
Cannot implicitly convert type 'Microsoft.EntityFrameworkCore.DbSet<FAQ.Models.QuestionAnswer>' to 'System.Linq.IQueryable<FAQ.Data.FAQContext.FAQContext>'. An explicit conversion exists (are you missing a cast?)CS0266
Angius
Angius4w ago
No description
Angius
Angius4w ago
We already went through that
strikeouts27
strikeouts27OP4w ago
My apologies I will look up asQueryable to understand what that is. AsQueryable(IEnumerable)
Converts an IEnumerable to an IQueryable.
Angius
Angius4w ago
Basically, yeah
strikeouts27
strikeouts27OP4w ago
I am getting a red squiggly line undder AsQueryable
public IActionResult Index(string topic, string category)
{
ViewBag.Topics = context.Topics.OrderBy(t => t.Name).ToList();
ViewBag.Categories = context.Categories.OrderBy(c => c.Name).ToList();
AsQueryable<FAQContext> faqs = context.FAQs
.Include(f => f.Topic)
.Include(f => f.Category)
.OrderBy(f => f.Question);

if (!string.IsNullOrEmpty(topic))
{
faqs = faqs.Where(f => f.TopicId == topic);
}
if (!string.IsNullOrEmpty(category))
{
faqs = faqs.Where(f => f.CategoryId == category);
}
return View();

}
public IActionResult Index(string topic, string category)
{
ViewBag.Topics = context.Topics.OrderBy(t => t.Name).ToList();
ViewBag.Categories = context.Categories.OrderBy(c => c.Name).ToList();
AsQueryable<FAQContext> faqs = context.FAQs
.Include(f => f.Topic)
.Include(f => f.Category)
.OrderBy(f => f.Question);

if (!string.IsNullOrEmpty(topic))
{
faqs = faqs.Where(f => f.TopicId == topic);
}
if (!string.IsNullOrEmpty(category))
{
faqs = faqs.Where(f => f.CategoryId == category);
}
return View();

}
it saying asqueryable cannot be found.
Angius
Angius4w ago
Probably because it's not how it's used It's not a type It's a method
IQueryable<Foo> foos = context.Foos.AsQueryable();
IQueryable<Foo> foos = context.Foos.AsQueryable();
It's used like this
strikeouts27
strikeouts27OP4w ago
public IActionResult Index(string topic, string category)
{
ViewBag.Topics = context.Topics.OrderBy(t => t.Name).ToList();
ViewBag.Categories = context.Categories.OrderBy(c => c.Name).ToList();
AsQueryable<FAQContext> faqs = context.FAQs
.Include(f => f.Topic)
.Include(f => f.Category)
.OrderBy(f => f.Question);

if (!string.IsNullOrEmpty(topic))
{
faqs = faqs.Where(f => f.TopicId == topic);
}
if (!string.IsNullOrEmpty(category))
{
faqs = faqs.Where(f => f.CategoryId == category);
}
return View();

}
public IActionResult Index(string topic, string category)
{
ViewBag.Topics = context.Topics.OrderBy(t => t.Name).ToList();
ViewBag.Categories = context.Categories.OrderBy(c => c.Name).ToList();
AsQueryable<FAQContext> faqs = context.FAQs
.Include(f => f.Topic)
.Include(f => f.Category)
.OrderBy(f => f.Question);

if (!string.IsNullOrEmpty(topic))
{
faqs = faqs.Where(f => f.TopicId == topic);
}
if (!string.IsNullOrEmpty(category))
{
faqs = faqs.Where(f => f.CategoryId == category);
}
return View();

}
oh i see
public IActionResult Index(string topic, string category)
{
ViewBag.Topics = context.Topics.OrderBy(t => t.Name).ToList();
ViewBag.Categories = context.Categories.OrderBy(c => c.Name).ToList();
IQueryable<FAQContext> faqs = context.FAQs.AsQueryable();
.Include(f => f.Topic)
.Include(f => f.Category)
.OrderBy(f => f.Question);

if (!string.IsNullOrEmpty(topic))
{
faqs = faqs.Where(f => f.TopicId == topic);
}
if (!string.IsNullOrEmpty(category))
{
faqs = faqs.Where(f => f.CategoryId == category);
}
return View();

}
public IActionResult Index(string topic, string category)
{
ViewBag.Topics = context.Topics.OrderBy(t => t.Name).ToList();
ViewBag.Categories = context.Categories.OrderBy(c => c.Name).ToList();
IQueryable<FAQContext> faqs = context.FAQs.AsQueryable();
.Include(f => f.Topic)
.Include(f => f.Category)
.OrderBy(f => f.Question);

if (!string.IsNullOrEmpty(topic))
{
faqs = faqs.Where(f => f.TopicId == topic);
}
if (!string.IsNullOrEmpty(category))
{
faqs = faqs.Where(f => f.CategoryId == category);
}
return View();

}
I am reading the documentation and it says that DBContext is the primary class for communicating with the database. DbSet<Entity> Is a collection of ojbects created from the specified entity. So an entity is an object created from a class activation, and those objects are stored in DbSet so that we can later access information for our project such as controllers and views.
Angius
Angius4w ago
Technically, nothing is stored before you query for it, but kinda, yeah DbContext represents the database, DbSets represent the tables
strikeouts27
strikeouts27OP3w ago
!close
Accord
Accord3w ago
Closed!

Did you find this page helpful?