The problem lies in SeedData

Abdou/Fawzy Aboyoussef 0 Reputation points
2024-11-20T01:48:47.58+00:00

I am following the article written by Rick Anderson about ASP.NET Core MVC web development with controllers and views. I face a fatal problem in the fifth part, working with a database. specifically the following statement in Program.cs:

app.MapStaticAssets();

Testing the app always fails and the following descriptions is generated:
//----------------------

Error (active) CS1061 'WebApplication' does not contain a definition for 'MapStaticAssets' and no accessible extension method 'MapStaticAssets' accepting a first argument of type 'WebApplication' could be found (are you missing a using directive or an assembly reference?) MvcMovie
//---------------------------------
I applied Rick's suggestions about forcing the app to read and to initialise the data unsuccessfully.
I don't want to quit, so, I would indear your help

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,636 questions
0 comments No comments
{count} votes

Accepted answer
  1. Zhi Lv - MSFT 32,456 Reputation points Microsoft Vendor
    2024-11-20T03:27:34.54+00:00

    Hi @Abdou/Fawzy Aboyoussef

    Error (active) CS1061 'WebApplication' does not contain a definition for 'MapStaticAssets' and no accessible extension method 'MapStaticAssets' accepting a first argument of type 'WebApplication' could be found (are you missing a using directive or an assembly reference?)

    For this error, it does not relate the seed method. It might relate that you didn't add the.NET 9 SDK and Runtime in your computer.

    So, you can check and try the following:

    1. Use the latest version Visual Studio and install the .NET 9.0 Runtime (via Visual Studio Installer) enter image description here
    2. Check the project file, make sure you are using the .net9.0 TargetFramework, and upgrade the related package to 9.0 version. enter image description here
    3. Open the project root folder, delete the bin and obj folder, and then re-build the application.

    Finally, if still not working, try to create a new .NET 9 MVC application and check whether it works or not.

    In my application, the Program.cs file like this:

    using Microsoft.EntityFrameworkCore;
    using WebApplication1.Models;
    var builder = WebApplication.CreateBuilder(args);
    builder.Services.AddDbContext<MvcMovieContext>(options =>
        options.UseSqlServer(builder.Configuration.GetConnectionString("MvcMovieContext") ?? throw new InvalidOperationException("Connection string 'MvcMovieContext' not found.")));
    // Add services to the container.
    builder.Services.AddControllersWithViews();
    var app = builder.Build();
    //Seed data 
    using (var scope = app.Services.CreateScope())
    {
        var services = scope.ServiceProvider;
        SeedData.Initialize(services);
    }
    // Configure the HTTP request pipeline.
    if (!app.Environment.IsDevelopment())
    {
        app.UseExceptionHandler("/Home/Error");
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }
    app.UseHttpsRedirection();
    //app.UseStaticFiles();
    app.MapStaticAssets();  //add MapStaticAssets()
    app.UseRouting();
    app.UseAuthorization();
    app.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}")
        .WithStaticAssets();
    app.Run();
    

    More information about the Seed Data, you can check the tutorial: work with a database in an ASP.NET Core MVC app.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,

    Dillion

    1 person found this answer helpful.
    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Abdou/Fawzy Aboyoussef 0 Reputation points
    2024-11-21T01:53:33.6833333+00:00

    Sincere and relevant response, however, it redirects to a range of possibilities that required varied readings, led to desperate experimantaions and generating more errors. I am a 90 years hobbiest. Fascinated but doesn't know what he is searching for. Not your job, be assured. In starting a new project, what, how and where to find what should be added to "using"? The list of existing items:

    using Microsoft.EntityFrameworkCore;

    using Microsoft.Extensions.DependencyInjection;

    using MvcMovie.Data;

    using MvcMovie.Models;

    In the program.cs file, where the statement that generated the error lies. which is:

    //----------------------------------------

    app.MapStaticAssets();

    //----------------------------------------------


  2. Zhi Lv - MSFT 32,456 Reputation points Microsoft Vendor
    2024-11-21T03:00:19.7533333+00:00

    Hi @Abdou/Fawzy Aboyoussef

    using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection;

    About the above using reference, since you are using EF core to work with a database, we need to add the EF core related packages: you can right click the project and select the "Manage NuGet Package..." operation, then in the Nuget panel, you can "Browse" the EF core related package and install them:

    User's image

    In my sample, I installed the following packages:

    	<ItemGroup>
    		<PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="9.0.0" />
    		<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="9.0.0" />
    		<PackageReference Include="Microsoft.AspNetCore.Identity.UI" Version="9.0.0" />
    		<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.0">
    		  <PrivateAssets>all</PrivateAssets>
    		  <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    		</PackageReference>
    		<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="9.0.0" />
    		<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="9.0.0" />
    	</ItemGroup>
    
    

    After that, when using the EF Core related methods, you could use the using statement to add the package reference.

    I suggest you could check this tutorial: Get started with ASP.NET Core MVC. And check the links one by one, it contains the detail steps to create MVC application and use EF core:

    User's image

    Error (active) CS1061 'WebApplication' does not contain a definition for 'MapStaticAssets'

    Besides, about the original question, might be you are not using the default template auto generated Program.cs file, or you are making a great changing. I suggest you can refer to my reply in this thread:

    From .NET 6, the new application template uses the New Hosting Model, it will unify Startup.cs and Program.cs into a single Program.cs file and uses top-level statements to minimize the code required for an app. So we can add services and middleware in the Program.cs file like this:

    65PWfkwB

    More detail information, see:

    New Hosting Model

    Code samples migrated to the new minimal hosting model in ASP.NET Core 6.0

    If you want to convert the application to use Startup.cs and Program.cs file. In the new template application, you can add a Startup.cs file and refer to the following code:

    Program.cs file:

        public class Program
        {
            public static void Main(string[] args)
            {
    
                var builder = WebApplication.CreateBuilder(args);
    
                // Set up logging
                builder.Logging.ClearProviders();
                builder.Logging.AddConsole();
                builder.Logging.AddDebug();
    
                // Create a logger factory to pass to Startup
                using var loggerFactory = LoggerFactory.Create(logging =>
                {
                    logging.AddConsole();
                    logging.AddDebug();
                });
                var logger = loggerFactory.CreateLogger<Startup>();
    
                // Initialize Startup and configure services
                var startup = new Startup(builder.Configuration, logger);
                startup.ConfigureServices(builder.Services);
    
                var app = builder.Build();
    
                // Configure the middleware pipeline
                startup.Configure(app, app.Environment);
    
                app.Run();
            }
        }
    
    

    Startup.cs file:

    using Microsoft.AspNetCore.Identity;
    using Microsoft.EntityFrameworkCore;
    using WebApplication2.Data;
    
    namespace WebApplication2
    {
        public class Startup
        {
            private readonly IConfiguration Configuration;
            private readonly ILogger<Startup> _logger;
            public Startup(IConfiguration configuration, ILogger<Startup> logger)
            {
                Configuration = configuration;
                _logger = logger;
    
                // Log a message during startup initialization
                _logger.LogInformation("Startup initialized.");
            }
            public void ConfigureServices(IServiceCollection services)
            {
                _logger.LogInformation("Configuring services...");
                services.AddControllersWithViews();
                services.AddRazorPages();
                // Add other services here
    
                //// Add services to the container.
                var connectionString = Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
                services.AddDbContext<ApplicationDbContext>(options =>
                    options.UseSqlServer(connectionString));
                services.AddDatabaseDeveloperPageExceptionFilter();
    
                services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
                    .AddEntityFrameworkStores<ApplicationDbContext>();
                services.AddControllersWithViews();
            }
    
            public void Configure(WebApplication app, IWebHostEnvironment env)
            {
                _logger.LogInformation("Configuring middleware...");
                // Configure the HTTP request pipeline.
                if (env.IsDevelopment())
                {
                    app.UseMigrationsEndPoint();
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                    app.UseHsts();
                }
    
                app.UseHttpsRedirection();
                app.UseRouting();
    
                app.UseAuthorization();
    
                app.MapStaticAssets();
                app.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}")
                    .WithStaticAssets();
                app.MapRazorPages()
                   .WithStaticAssets();
            }
        }
    }
    
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,

    Dillion

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.