context = new ApplicationDbContext();
context.Clients.Add(item);
InvalidOperationException: nessun provider di database è stato configurato per questo DbContext. Un provider può essere configurato eseguendo l'override del metodo DbContext.OnConfiguring o utilizzando AddDbContext sul provider del servizio dell'applicazione. Se si utilizza AddDbContext, assicurarsi inoltre che il tipo DbContext accetti un oggetto DbContextOptions nel suo costruttore e lo passi al costruttore di base per DbContext.
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public ApplicationDbContext()
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}
public DbSet<Client> Clients { get; set; }
Avviare
public class Startup
{
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();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddMvc();
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseIdentity();
// Add external authentication middleware below. To configure them please see https://go.microsoft.com/fwlink/?LinkID=532715
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
aggiornato
Ho aggiunto
// Startup.ConfigureServices
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
//////my=>
services.AddDbContext<DbContext>(config =>
{
config.UseSqlServer(Configuration.GetConnectionString("Default"));
});
e configuralo nel tuo appsettings.json
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-WebApplicationCore-42a4ac05-477c-4ea7-b286-87423170b48a;Trusted_Connection=True;MultipleActiveResultSets=true",
"Default": "Server=(localdb)\\mssqllocaldb;Database=aspnet-WebApplicationCore-42a4ac05-477c-4ea7-b286-87423170b48a;"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
}
}
Ho fatto clic sul file appsettings.json e ho modificato le proprietà nella finestra delle proprietà in "Build Action: Content" e "CopyToOutputDirectory: Copy Always"
<ItemGroup>
<Content Update="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
Errore non risolto
Nuovo errore:
var result = await _userManager.CreateAsync(user, model.Password);
Si è verificata un'eccezione non gestita durante l'elaborazione della richiesta. SqlException: si è verificato un errore relativo alla rete o specifico dell'istanza durante la creazione di una connessione a SQL Server. Il server non è stato trovato o non era accessibile. Verificare che il nome dell'istanza sia corretto e che SQL Server sia configurato per consentire le connessioni remote. (provider: Interfacce di rete SQL, errore: 50 - Si è verificato un errore di Database Database locale. Ð'о Ð²Ñ € ÐμÐ¼Ñ Ð · Ð ° Ð¿ÑƒÑ ÐºÐ ° Ñ ÐºÐ · ÐμпР»Ñ Ñ € Ð ° LocalDB Ð¿Ñ € оР¸Ð · оÑÐ »Ð ° оÑиР± кР°: оÑиР± кР° Ð · Ð ° Ð¿ÑƒÑ ÐºÐ ° Ð¿Ñ € л Ð »Ñ Ð ° SQL Server.)
System.Data.SqlClient.SqlInternalConnectionTds..ctor (DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, object providerInfo, boir redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, bool applyTransientFaultHandling)
Non è possibile creare un'istanza di DbContext senza un costruttore con parametri o un override su OnConfiguring
.
Hai due scelte:
Passa DbContextOptions<ApplicationDbContext>
tramite DI al tuo ApplicationDbContext
. Ciò è più semplice configurando ApplicationDbContext
nel tuo startup.cs e risolvendolo (senza usare new
parole chiave !!!)
// Startup.ConfigureServices
services.AddDbContext<DbContext>(config =>
{
config.UseSqlServer(Configuration.GetConnectionString("Default"));
});
e configuralo nel tuo appsettings.json
{
"ConnectionStrings": {
"Default": "YourSQLConnectionStringHere"
}
}
Meno consigliato, poiché richiede l'hardcoding della stringa di connessione, l'approccio è configurarlo all'interno di DbContext
public class ApplicationDbContext
{
public ApplicationDbContext(DbContextOptions options) : base(options)
{
}
// The call of the base constructor via ": base()" is still required
public ApplicationDbContext(DbContextOptions options) : base()
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(Configuration.GetConnectionString("connectionStringHere"));
base.OnConfiguring(optionsBuilder);
}
}
In risposta ai commenti, è necessario aggiungere
<ItemGroup>
<Content Update="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
per copiare appsettings.json nella directory di output. Oppure fai semplicemente clic sul file appsettings.json e modifica le proprietà nella finestra delle proprietà in "Build Action: Content" e "CopyToOutputDirectory: Copy Always"