Not able to configure connection string in ASP.net MVC Core 5.0 & Entity Framework Core application - asp.net-core

I'm getting below error when I configure SQL Connection in ASP.Net Core MVC 5 and Entity Framework core.
I've configured in Startup.cs file:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddDbContext<VMSDBContext>(
options => options.UseSqlServer(Configuration.GetConnectionString("VMSDatabase"))
);
}
My appsettings.json file:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"ConnectionStrings": {
"VMSDatabase": "Server=.;Database=VMS;Trusted_Connection=True;"
},
"AllowedHosts": "*"
}
InvalidOperationException: No database provider has been configured for this DbContext. A provider can be configured by overriding the 'DbContext.OnConfiguring' method or by using 'AddDbContext' on the application service provider. If 'AddDbContext' is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.

You're looking for a connection called "VMSDatabase" in your code. But you've configured a connection called "AgileOneVMSDatabase" in your appsettings. Change either one of them so to the same and this should solve your issue.

According to your description, I guess the reason why you faced this issue is you used the wrong VMSDBContext's constructor method. If this class's
constructor method doesn't contains the DbContextOptions parameter, it will face this error.
I suggest you could change it like below:
public VMSDBContext(DbContextOptions options) : base(options) {}

Related

How to configure .NET Core logging json file to ignore certain events?

I would like to ignore certain warnings in prod system. The code equivalent I was given is this:
optionsBuilder
.ConfigureWarnings(x => x.Ignore(RelationalEventId.MultipleCollectionIncludeWarning));
Is it possible to set the ignore in appSettings.Production.json instead?
Currently it is:
"Logging": {
"LogLevel": {
"Default": "Trace",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information",
"Microsoft.EntityFrameworkCore": "Warning",
"IdentityServer4": "Information"
}
},
I'm not an EF Core expert, but it seems evident these are two different types of configuration; the builder call is telling EF Core what events to log or not, and the appsettings is just instructing the logging framework which providers to listen to at which levels. You might be able to mute the entire provider at a given log level, but that would likely not be granular enough to filter just a certain class of log events within that provider.
If EF Core does not have a native mechanism for reading in an Options class from a Configuration object and you have a limited set of switches you'd want to manage (i.e. just a single group of things that may be turned on or off together), then you can write your own to help manage it.
Configuration class:
public class CustomEfCoreLoggingOptions
{
public const string Section = "CustomEfCoreLogging";
public bool IgnoreMultipleCollectionIncludeWarning { get; set; }
}
Appsettings:
"CustomEfCoreLogging" : {
"IgnoreMultipleCollectionIncludeWarning" : true
}
In your startup:
var efLogging = Configuration.GetSection(CustomEfCoreLoggingOptions.Section).Get<CustomEfCoreLoggingOptions>();
var optionsBuilder = new DbContextOptionsBuilder();
if (efLogging.IgnoreMultipleCollectionIncludeWarning) optionsBuilder.ConfigureWarnings(x => x.Ignore(RelationalEventId.MultipleCollectionIncludeWarning));
//...

No database provider has been configured for this DbContext .NET Core with SQL Server

I have been banging my head against a wall with this one and have been googling to no avail.
I have just started a new ASP.NET Core MVC project, I have installed/updated my packages for these two to 2.2.0:
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools
I have set the project to expect .NET Core 2.2.0 as well.
I am able to successfully add my table schemas with this command in Package Manager console to scaffold the Database, so I know the connection string is fine/working:
Scaffold-DbContext "SERVER=Server\Instance;DATABASE=Database;UID=user;PWD=password;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Tables Table1, Table2, Table3
The created model file, DatabaseDBContext.cs looks like this:
public partial class DatabaseDBContext : DbContext
{
public DatabaseDBContext()
{
}
public DatabaseDBContext(DbContextOptions<DatabaseDBContext> options)
: base(options)
{
}
}
This also contains a method that works to retrieve my scaffold data, but isn't considered safe for production use so I commented this out:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer("SERVER=Server\\Instance;DATABASE=Database;UID=user;PWD=password;");
}
}
I added this same connection string to the appsettings.json file:
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
},
"ConnectionStrings": {
"DBConnString": "SERVER=Server\\Instance;DATABASE=Database;UID=user;PWD=password;"
}
}
I then added the DbContext to the startup.cs file:
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddDbContext<DatabaseDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DBConnString")));
}
Trying to add a new scaffolded controller for one of the tables throws this error:
Finding the generator 'controller'...
Running the generator 'controller'...
Attempting to compile the application in memory.
Attempting to figure out the EntityFramework metadata for the model and DbContext: 'TableName'
No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.
StackTrace:
at Microsoft.EntityFrameworkCore.Internal.DbContextServices.Initialize(IServiceProvider scopedProvider, IDbContextOptions contextOptions, DbContext context)
at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
at Microsoft.EntityFrameworkCore.Internal.InternalAccessorExtensions.GetService[TService](IInfrastructure1 accessor)
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func1 factory)
No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.
Has anyone got any clue what I am doing wrong here?
So I fixed but it in a really roundabout way. My new project was originally on an older version of .net core. I had updated the version but there must have been something it didn't like during the update. I created a new project and started it on 2.2.0, then it worked...
The code logic was sound above. Still needed the same packages:
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools
Startup.cs seems quite different, so maybe if anyone else sees this they could try updating the startup.cs code:
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddDbContext<DatabaseDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DatabaseDBConnString")));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
Had to add a reference to startup.cs for this:
using Microsoft.EntityFrameworkCore;
That was needed for the AddDbContext method to resolve.
After doing this the scaffolding now works. So it's fixed, but it required me to start over to fix it.
I had the same problem and this solved it for me (setting UseSqlServer in OnConfiguring):
protected override void OnConfiguring(DbContextOptionsBuilder builder)
{
if (!builder.IsConfigured)
{
string conn = this.IsProduction ? Const.ProductionConnectionString : Const.LocalDBConnectionString;
builder.UseSqlServer(conn);
}
base.OnConfiguring(builder);
}
After battleing with this issue I've encounter the solution for it here
https://github.com/aspnet/EntityFrameworkCore/issues/12331
The problem was that Add-Migration was expecting the CreateWebHostBuilder
public static IWebHostBuilder CreateWebHostBuilder(string[] args)
Before my public static void Main(string[]) was running the WebHost without the static CreateWebHostBuilder and that after I added the Static function then it worked.
I had this problem after I've inlined Program.CreateWebHostBuilder into Program.Main. Had to extract it back.
It was wired but fixed this issue by updating the framework version of the project solution. For example, I created one core repo on 3.0 and later installed the latest version 3.1 on the system so it was expecting to be updated with the latest version. I changed it and it worked!
Try add this 3rd constructor:
public DatabaseDBContext()
{
}
public DatabaseDBContext(DbContextOptions<DatabaseDBContext> options)
: base(options)
{
}
public DatabaseDBContext(DbContextOptions options)
: base(options)
{
}
Then chuck a breakpoint in each one just so you are sure which one is actually getting used.

DbContext class in .Net Core

Hi Guys I am trying to migrate from Asp.Net MVC 5 to .Net Core 2.0 Web Application.
I am stuck with a error saying :
Cannot convert from 'string' to
'Microsoft.EntityFrameworkCore.DbContextOptions'
I get the above error when I hover over the class:
public class ExampleModelWrapper : DbContext
{
public ExampleModelWrapper()
: base("name=EXAMPLE_MODEL")
{
}
}
ExampleModelWrapper is a model.
I referred to the following question in stack overflow:
How can I implement DbContext Connection String in .NET Core?
I have the connection string in appsettings.json:
{
"ConnectionStrings": {
"EXAMPLE_MODEL": "Server=(localdb)\\mssqllocaldb;Database=aspnet-Monitoring-CCA7D047-80AC-4E36-BAEA-3653D07D245A;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
}
}
I have provided the service in startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("EXAMPLE_MODEL")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
// Add application services.
services.AddTransient<IEmailSender, EmailSender>();
services.AddMvc();
}
What can be the reason for the above error. I believe a connection is being established to the database successfully ,as it is working for the login and registration flow of Identity Db.I am also stumped on how or where to change the connections for the identity Db. Help appreciated , Thank you!!
You need to use the following constructor in your DbContext
public ExampleModelWrapper (DbContextOptions<ExampleModelWrapper> options)
: base(options)
{
}
Within your startup, you need to modify the following:
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("EXAMPLE_MODEL")));
to the following:
services.AddDbContext<ExampleModelWrapper>(options =>
options.UseSqlServer(Configuration.GetConnectionString("EXAMPLE_MODEL")));
Basically, you need to specify the DbContext you need to use.

ASP.NET Core MVC App Settings

I'm trying to use configuration variables on my ASP.NET Core MVC project.
This is where I've got so far:
Created an appsettings.json
Created an AppSettings class
Now I'm trying to inject it on the ConfigureServices, but my Configuration class is either not recognized or when using the full reference: "Microsoft.Extensions.Configuration" the GetSection Method is not recognized, i.e.
Configuration class not being recognized
GetSection method not being recognized
Any ideas on how to use this?
The whole configuration approach in .NET Core is really flexible, but not at all obvious at the beginning. It's probably easiest to explain with an example:
Assuming an appsettings.json file that looks like this:
{
"option1": "value1_from_json",
"ConnectionStrings": {
"DefaultConnection": "Server=,\\SQL2016DEV;Database=DBName;Trusted_Connection=True"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
}
}
To get the data from appsettings.json file you first need to set up a ConfigurationBuilder in Startup.cs as follows:
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsDevelopment())
{
// For more details on using the user secret store see https://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets<Startup>();
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
You can then access the configuration directly, but it's neater to create Options classes to hold that data, which you can then have injected into your controller or other classes. Each of those options classes represent a different section of the appsettings.json file.
In this code the connections strings are loaded into a ConnectionStringSettings class and the other option is loaded into a MyOptions class. The .GetSection method gets a particular part of the appsettings.json file. Again, this is in Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
... other code
// Register the IConfiguration instance which MyOptions binds against.
services.AddOptions();
// Load the data from the 'root' of the json file
services.Configure<MyOptions>(Configuration);
// load the data from the 'ConnectionStrings' section of the json file
var connStringSettings = Configuration.GetSection("ConnectionStrings");
services.Configure<ConnectionStringSettings>(connStringSettings);
These are the classes that the settings data are loaded into. Note how the property names pair up with the settings in the json file:
public class MyOptions
{
public string Option1 { get; set; }
}
public class ConnectionStringSettings
{
public string DefaultConnection { get; set; }
}
Finally, you can then access those settings by injecting an OptionsAccessor into the controller as follows:
private readonly MyOptions _myOptions;
public HomeController(IOptions<MyOptions > optionsAccessor)
{
_myOptions = optionsAccessor.Value;
var valueOfOpt1 = _myOptions.Option1;
}
Generally, the whole configurations settings process is pretty different in Core. Thomas Ardal has a good explanation of it on his site here: http://thomasardal.com/appsettings-in-asp-net-core/
There's also a more detailed explanation of Configuration in ASP.NET Core in the Microsoft documentation.
NB: This has all evolved a bit in Core 2, I need to revisit some of the answer above, but in the meantime this Coding Blast entry by Ibrahim Ĺ uta is an excellent introduction with plenty of examples.
NB No. 2: There are a number of configuration mistakes that are easy to make with the above, have a look at this answer if it doesn't behave for you.
tomRedox 's answer was highly helpful - Thanks.
Also, I've changed the following references to the following versions, to get it working.
"Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.2",
"Microsoft.Extensions.Configuration.Json": "1.1.1"

Setting Up ASP.NET Identity Core in an empty ASP.NET Core Web Application

I am trying to start a new web application project and I wanted to use the asp.net identity database (the one with all the AspNet tables (AspNetUsers, AspNetRoles etc)).
I have tried to follow numerous guides, these among other:
bitoftech.net/2015/01/21/asp-net-identity-2-with-asp-net-web-api-2-accounts-management/
johnatten.com/2014/04/20/asp-net-mvc-and-identity-2-0-understanding-the-basics/
tektutorialshub.com/asp-net-identity-tutorial-basics/%20%22ASP.Net%20Identity%20Tutoria
benfoster.io/blog/aspnet-identity-stripped-bare-mvc-part-1
However when I tried to create the database I get this error.
I have also tried to do it by mimicking the template project (ASP.NET Core Web Application(.Net Core)) in Visual Studio with the same result or this one
This is how my project looks like, its basically the template minus the Controllers, Views and Models.
Startup.cs
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath);
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
//var connectionString = #"Data Source=(localdb)\mssqllocaldb;Initial Catalog=Northwind;Integrated Security=True;Pooling=False";
//services.AddEntityFramework()
// .AddSqlServer()
// .AddDbContext<NorthwindContext>(o =>
// o.UseSqlServer(connString));
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app)
{
app.UseDeveloperExceptionPage();
app.UseStaticFiles();
app.UseIdentity();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
ApplicationUser.cs
public class ApplicationUser : IdentityUser
{
}
ApplicationDbContext.cs
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
}
}
I just want to have an empty project with asp.net identity, preferably in SQL server instead of in localdb. Does anyone have a easy guide or know why it does not work for me?
EDIT1
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext() : this("Data Source=ACLAP;Initial Catalog=tmpCore;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False") { }
}
EDIT2
I have put up the project on github.
github.com/KiBlob/test
Just an idea, do you have defined the DefaultConnection in your appsettings.json file?
Mine looks like this:
{
"ConnectionStrings": {
"DefaultConnection": "Server=[SERVER];Database=[DB];Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}
Try setting the connection there and then run Update-Database again.
Note: If you have multiple projects in your solution, make sure that the Default project in the package manager console is pointing to the project where the connection is set before running Update-Database.