Screencast Build a Character Database App With .NET MVC .NET

  • Eric J Fisher


  1. Panny said

    I have a problem when i run "dotnet run". The error shows “A namespace does not directly contain members such as fields or methods” in Application Db Context, how could i fix this?

  2. Faculty

    Eric J Fisher said

    Hello @Panny, Based on the error you're receiving it sounds like you you have placed a field or property outside of your class (and thus inside your namespace)

    Something like this... namespace WebApplication.Data { public DBSet<Player> Players { get; set;} public class ApplicationDbContext...

    when it should be like this... namespace WebApplication.Data { public class ApplicationDbContext { public DbSet<Player> Players { get; set } ...

    At least that's what I'd guess based on the error you're receiving. (In either case the compiler thinks you're trying to use a field or method outside of a class) if you you look in the bottom left corner of Visual Studio code you should see a little X in a circle. Click on that and it'll show you code errors such as the one you're running into. (should even show you what line of code is at fault) Hope that helps!

  3. Camilo Riviere said

    I'm getting an error when using this code:

    using (var serviceScope = app.ApplicationServices.GetRequiredService .CreateScope()) { serviceScope.ServiceProvider.GetService() .Database.EnsureDeleted(); serviceScope.ServiceProvider.GetService() .Database.EnsureCreated(); }

  4. Faculty

    Eric J Fisher said

    @CamiloRiviere I'm not spotting a problem just with what you've posted it's possible you might be missing using Microsoft.EntityFrameworkCore; from the top of your StartUp.cs file. Other than that I'd probably need to see the actual error you're getting to really be able to provide more help :(

  5. Camilo Riviere said

    Hi Eric, I ran the application and this is what I get when I try to access localhost.../Players

    fail: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[0]

    An unhandled exception has occurred: SQLite Error 1: 'no such table: Players'.

    fail: Microsoft.EntityFrameworkCore.Query.RelationalQueryCompilationContextFactory[1]

  6. Faculty

    Eric J Fisher said

    Gotcha! sounds like you still need to add dbset<Player> Player { get; set; } to your ApplicationDbContext.cs if not that it could also potentially be you're missing services.AddDbContext<ApplicationDbContext>(options => options.UseSqlite(Configuration.GetConnectionString("DefaultConnection"))); from your Startup.cs's 'ConfigureServices' method. Here's a link to the repository if you would like to compare your Startup.cs and ApplicationDbContext.cs files with what I had at the end of the watch us build video.

  7. Faculty

    Eric J Fisher said

    Correction that should be dbset<Player> Players { get; set; } teaches me to not proof read :/

  8. Camilo Riviere said

    Also, when I use the segment of code that I previously mentioned this is the error I get: /Users/Crivi002/Desktop/OneDrive/CodeSchool/NET/ScoreKeeper/Startup.cs(75,67): error CS0119: 'ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider)' is a method, which is not valid in the given context

  9. Camilo Riviere said

    Sorry to bug you Eric but I didn't get the link to the repository to make the comparisons...

  10. Camilo Riviere said

    Disregard... I found it!

  11. Camilo Riviere said

    I got it to work: I believe what I didn't have added was the following: template: "{controller=Player}/{action=Index}/{id?}");

    before controller was assigned a value of "Home"

  12. Faculty

    Eric J Fisher said

    Awesome :) Troubleshooting is probably the most time consuming part of software development, glad to hear you got it all sorted.

  13. douwejan said

    Where is the source code?

  14. Jackslaps said

    Hi, I'm getting a problem with my Startup.cs file, when I insert the code you gave us so that we don't have to use migrations:

    using (var serviceScope = app.ApplicationServices.GetRequiredService.CreateScope()) { serviceScope.ServiceProvider.GetService() .Database.EnsureDeleted(); serviceScope.ServiceProvider.GetService() .Database.EnsureCreated(); }

    It's highlighting the .GetRequiredService and it's saying that it is a method, and that it not valid in the given context.

    I used the command you used for creating the template (dotnet new -t web). I don't know why this is happening :(

  15. Faculty

    Eric J Fisher said

    Sorry, I think perhaps some characters are getting stripped from the comments here. Here's a link directly to what I have in the github repo (specifically I think it's missing the parts between the angle brackets)

  16. Jackslaps said

    Hey can you guide me towards a good article that shows how to set the environment to development, the site is not loading at all and its telling me to change to dev mode

  17. Jackslaps said

    and thank you for your help before, i was having a hard time with that

  18. Faculty

    Eric J Fisher said

    So the best I've found for reading through was this The big thing here is we want to set the ASPNETCORE_ENVIRONMENT variable to Development. There are a large number of ways to do this that "work", but I'd personally use this way.

  19. Mengyi Yuan said

    Very nice hands-on practice. Now everything binds together. Thanks!

  20. Mengyi Yuan said

    Wow, there is something I totally do not expect. When I submit my comment, the whole page reloads, which means the video also reloads. I think we probably don't want that. :)

  21. Faculty

    Eric J Fisher said

    @Mengyi Thank you for the compliments :) Iall also send your feedback to our devs to look into, that is a good point because losing your place in something well over 15 minutes long is exactly a great experience.

  22. wangxianhui1021 said

    When I type dotnet run in the terminal, I can see the standard pages but when I went to http://localhost:5000, there is this : "Error. An error occurred while processing your request. Development Mode Swapping to Development environment will display more detailed information about the error that occurred.

    Development environment should not be enabled in deployed applications, as it can result in sensitive information from exceptions being displayed to end users. For local debugging, development environment can be enabled by setting the ASPNETCORE_ENVIRONMENT environment variable to Development, and restarting the application." Could you please help?

  23. wangxianhui1021 said

    *Correction I went to http://localhost:5000/Player that's when I saw the error

  24. Faculty

    Eric J Fisher said

    What this is saying is there has been an error, but by default you're an production so it hides the error specifics (as when your application is actually in use by other people providing all the details can potentially be a security risk) In your case though you're developing it locally so you'll want to see all these error details so you can diagnose and correct them.

    Now setting up environment variables varies heavily depending on what operating system you're using. You also could have dozens of way to set them based on what tools you're using that vary tool to tool.

    Instead we're going to just skip that for now, inside your StartUp.cs file you'll see the line app.UseExceptionHandler("/Home/Error"); in your configure method. Change that to app.UseDeveloperExceptionPage(); once you save that change and run the application again you should see what the actual error is.

    Based on my experience when you get these errors attempting to access an error the issue is typically going to be in the view, or the model the view is using. (it can be other places, but most other errors will throw errors before the program even runs rather than when you attempt to access a specific part of the application.)

    I hope that helps :)

  25. Christopher DEBOVE said

    Great quality screencast like always. I love coding the project on the same time, i'm looking the video. Really cool work !

  26. HATEM SAIDANE said

    Hi; It looks like the application works fine as long as there's one player, the id is set to 0 for all players? Unless I'm missing something , I don't see how the Id is unique and being increment as needed for each user? To go around this I modified the PlayerController to increment the id (ei: var model = _context.Players.LastOrDefault(e => e.Name != null, then update Player Id ==> int indx = model.Id +1, Player.Id = indx...). Is that correct? Thanks

  27. Faculty

    Eric J Fisher said

    Hello Hatem! I think something might be getting overlooked. Entity Framework should create the Id property on the Player table regardless of if we explicitly declare it or not. This field will be a unique identifier by default and automatically increment by 1 each time a new record is saved. (the Id populates at the time you run the SaveChanges() method, if you look before that point it'll be either null or 0, in either case after you call SaveChanges() it should change to something else)

    If for some reason the Id is NOT auto incrementing you can try adding the [key] attribute above the Id property, or something that's been typed in is overriding this behavior. You could manually update the Id by grabbing whatever player has the highest Id then add 1 (I wouldn't bother with the checking Name for null. Let's say whether by mistake or intentionally we permit new players without names to be added to the database, we would still want all those records to have an id. So you could do var player.Id = _context.Players.LastOrDefault().Id + 1; (where player is the current player you are creating)

    In any case I'd just try it without the manual process, see if the Id is auto incrementing, if not try adding the [key] attribute to the Id property. It's probably best to use the auto-incrementing for both performance and data integrity reasons. (manually updating the Id can be potentially risky as when a system scales and you have many records being created at the same time a whole mess of things can potentially go wrong)

  28. HATEM SAIDANE said

    I placed the [key] on top of the name and not the Id in the Player.cs, and this was the root cause of the problem. I removed the [key] attribute and now the 'Id' is incremented properly when adding players....


  29. Alec Meyer said

    Nicely done.

  30. Joe Hutchins said

    What is the alternative to using 'dotnet new -t web' since it doesn't seem like there's an option for it in terminal? When I use 'dotnet new web' or any of the other templates available, it's missing half the other files shown during setup. I also get the following error when I copy the lesson plan from the github repo and type 'dotnet restore': MSBUILD : error MSB1003: Specify a project or solution file. The current working directory does not contain a project or solution file.

  31. Faculty

    Eric J Fisher said

    I'll get the repo updated to the latest version of .NET. Unfortunately a recent update had a lot of breaking changes in regards to how you create and run an application. So where we would use dotnet new -t web it changed to just dotnet new web the project files also changed from including a project.json file in json to a .csproj file in xml. In the mean time you can create a new project using dotnet new web and follow along with the watch us build as outside of the project file changes and templating not much changed.

  32. Faculty

    Eric J Fisher said

    We'll also make minor corrections to this recording to make it accurate to the latest version as well.

  33. Faculty

    Eric J Fisher said

    Actually one more correction you want to use dotnet new mvc not dotnet new web (sorry give the wrong template) :(

  34. NottinghamDerm said

    I seem to be getting this error message whenever I try to run the application from the terminal:

    Unhandled Exception: System.MissingMethodException: Method not found: 'System.IServiceProvider Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(Microsoft.Extensions.DependencyInjection.IServiceCollection)'. at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build() at ScoreKeeper.Program.NewMethod() in /Users/damonmorris/Documents/ProgrammingProjects/ScoreKeeper/Program.cs:line 21 at ScoreKeeper.Program.Main(String[] args) in /Users/damonmorris/Documents/ProgrammingProjects/ScoreKeeper/Program.cs:line 14

    It seems to be in the Program.cs file, although no changes were made to this file?

  35. Faculty

    Eric J Fisher said

    I wasn't able to get the specific error you're seeing, but there were a few problems I found that may or may not be related that came from my updating the solution to .Net Core 1.1.3 (everything discussed in this video is still valid, but I had to update the project files which had some side effects)

    I can confirm there was an issue in the Startup.cs file where it would crash on OSX because I failed to change it back to using Sqlite so it wound up using MsSql which didn't work for OSX users.

    I also changed the namespace away from MyApplication during my update and missed a few views which caused problems.

    I'd recommend grabbing a fresh copy of the repository and trying again. (The error above appears to be complaining about a NewMethod which doesn't really make sense, but I can confirm the latest version on github works on both windows and OSX whether you use Visual Studio or Command Line/Terminal.

    Let me know if you still have any issues.

  36. WILLIAMSJ12 said

    Loaded the completed code from GitHub into VS Code (Latest Version). Able to build with No errors and get the service running after installing a few packages. However when executing in the browser to connect I get the following database error:

    info: Microsoft.EntityFrameworkCore.Storage.IRelationalCommandBuilderFactory[1] Executed DbCommand (2ms) [Parameters=[], CommandType='Text', CommandTimeout='30'] SELECT "p"."Id", "p"."Name" FROM "Players" AS "p" fail: Microsoft.EntityFrameworkCore.Query.RelationalQueryCompilationContextFactory[1] An exception occurred in the database while iterating the results of a query. Microsoft.Data.Sqlite.SqliteException: SQLite Error 1: 'no such table: Players'.

    When trying to run the 'dotnet ef database update' command in the terminal window as suggested, I get error MSB1009: Project file does not exist.

    Thanks for any insight on this issue.

  37. Faculty

    Eric J Fisher said

    Thank you for pointing this out! It appears in the last few updates to VS Code and Visual Studio the tool changed from defaulting to "Production" but "Development" (which in my opinion is a very good thing! but.... it broke our application here since we don't really deal with environment at a real level)

    I've updated the repository with a fix, so you can just pull the latest and be good to go! (I addressed this issue by moving where we create our database in the StartUp.cs's Configure method to be outside our condition that checks what environment we're running in.

    The project file does not exist is probably you need to navigate directly to where the csproj file is located and can't run it at the project's root directory. (but that command shouldn't be needed)

    Let me know if it still gives you any trouble!

About This Screencast

In this episode, we will take what we learned in the Forging Ahead With ASP.NET Core course and create a simple scorekeeping application using ASP.NET MVC. We will also demonstrate how to set up and connect Entity Framework to serve up the data from the database.

You need to be an enrolled student in order to view this video and subscribe.

Enroll Now