0

I want to update my migrated database on my Asp.Net Core MVC Application, but I get the following error when I try to do this:

I have already tried a few tutorials or forum posts but unfortunately it didn't work. Could someone help me please?

That's my Startup.cs:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json.Serialization;
using PlaudertischSoftware.Models;
using Pomelo.EntityFrameworkCore.MySql;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.HttpOverrides;
using System.Net;
using Microsoft.AspNetCore.Http;

namespace PlaudertischSoftware
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
            services.AddRazorPages();
            services.AddMvc()
                .SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
            services.AddMvc(option => option.EnableEndpointRouting = false);
            services.AddDbContext<DatenbankKontext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("MyConnectionString")));
            services.AddControllersWithViews()
                .AddJsonOptions(options =>
                {
            options.JsonSerializerOptions.PropertyNamingPolicy = null;
                });
            services.Configure<ForwardedHeadersOptions>(options =>
            {
                options.KnownProxies.Add(IPAddress.Parse("0.0.0.0"));
            });

        }
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
            });

            app.UseAuthentication();
        }
    }
}

Here's my Program.cs:

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.HttpSys;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using PlaudertischSoftware.Models;
using System.IO;

namespace PlaudertischSoftware
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
               .UseKestrel()
               .UseUrls("http://*:5000")
               .UseContentRoot(Directory.GetCurrentDirectory())
               .UseIISIntegration()
               .UseStartup<Startup>()
               .Build();

            host.Run();
        }
    }
}

My ContextFactory:

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.EntityFrameworkCore.Infrastructure;
using PlaudertischSoftware.Models;

namespace PlaudertischSoftware
{
    public class DatenbankKontextFactory : IDesignTimeDbContextFactory<DatenbankKontext>
    {
        public DatenbankKontext CreateDbContext(string[] args)
        {
            var optionsBuilder = new DbContextOptionsBuilder<DatenbankKontext>();
            optionsBuilder.UseSqlServer("MyConnectionString");

            return new DatenbankKontext(optionsBuilder.Options);
        }
    }
}

That's my appsettings.json:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "MyConnectionString": "Server=(localdb)\\mssqllocaldb;Database=MyConnectionString;Integrated Security=True"
  }
}
1
  • But I don't have a .mdf File. In my Application the Controller creates a database and updates it dynamically Commented Mar 30, 2020 at 13:13

1 Answer 1

1

I think the problem is here:

    public DatenbankKontext CreateDbContext(string[] args)
    {
        var optionsBuilder = new DbContextOptionsBuilder<DatenbankKontext>();

        optionsBuilder.UseSqlServer("MyConnectionString");
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

        return new DatenbankKontext(optionsBuilder.Options);
    }

That UseSqlServer is expecting an actual connection string, and you're passing it a string of "MyConnectionString" which is only the name you've called your connection string config entry, but UseSqlServer won't take it and go rummaging in your appsettings.connectionstrings looking for something with that name; it'll just take it as if it were a connection string and try to use it

I would have expected it to look more like your other line (in the services registration) which is:

optionsBuilder.UseSqlServer(Configuration.GetConnectionString("MyConnectionString"));

Actually, I'm not even really sure what your DatenbankKontextFactory is hoping to do that the DbContext creator you've already registered with DI isn't doing? If you want a DbContext for some reason and the one provided for you by DI is no good (wrong scope?) then you can ask DI to make you another one, perhaps with a different scope

Sign up to request clarification or add additional context in comments.

1 Comment

Oh yes you're right. The DatenbankKontextFactory is completely useless. I already have a dbcontext. I had that from some confusing internet tutorials

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.