I'm meant to call this method at startup but it's not reference anywhere:
dbContext.Database.Migrate();
Type DatabaseFacade does not contain a definition for Migrate and no
extension method Migrate of type DatabaseFacade could be found (are you missing
a using directive or an assembly reference?
So which using / assembly am I missing?
I needed to add the following dependencies via NuGet.
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.SqlServer
Just import EntityFrameworkCore by typing the following at the top:
using Microsoft.EntityFrameworkCore;
var migrator = dbContext.Database.GetService<IMigrator>();
await migrator.MigrateAsync("targetMigration", cancellationToken);
(For.Net Core) After adding the package (Oracle/SQLServer)
enter image description here
you can design the startup.cs like this using extensions.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app
.UseSwaggerUI()
.UseRouting()
.UseCors(options => options
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod())
.UseAuthentication()
.UseAuthorization()
.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
})
.ApplyMigrations();
}
So you can call ApplyMigrations as below.
using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
namespace SocialRebate.WebApi.Infrastructure.Extensions
{
public static class ApplicationBuilderExtensions
{
public static IApplicationBuilder UseSwaggerUI(this IApplicationBuilder app)
=> app
.UseSwagger()
.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "Your API");
options.RoutePrefix = string.Empty;
});
public static void ApplyMigrations(this IApplicationBuilder app)
{
using var services = app.ApplicationServices.CreateScope();
var dbContext = services.ServiceProvider.GetService<YourDbContext>();
dbContext.Database.Migrate();
}
}
}
In the constructor of your DataContext class you can use
this.Database.Migrate();
and it should do just fine.
Related
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;
using Travel.Application;
using Travel.WebApi.Filters;
using Travel.Data;
using Travel.Shared;
namespace Travel.WebApi
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddApplication();
services.AddInfrastructureData();
services.AddInfrastructureShared(Configuration);
services.AddHttpContextAccessor();
services.AddControllers();
services.AddControllersWithViews(options =>
options.Filters.Add(new ApiExceptionFilter()));
services.Configure<ApiBehaviorOptions>(options =>
options.SuppressModelStateInvalidFilter = true
);
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Travel.WebApi", Version = "v1" });
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Travel.WebApi v1"));
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
So this is my "StartUp" file and I have an error that says :
Severity Code Description Project File Line Suppression State
Error CS1061 'IServiceCollection' does not contain a definition for
'AddInfrastructureData' and no accessible extension method
'AddInfrastructureData' accepting a first argument of type
'IServiceCollection' could be found (are you missing a using directive
or an assembly
reference?) Travel.WebApi C:\Users\Alexandru\Desktop\WebDev\AdminApp\src\presentation\Travel.WebApi\Startup.cs 26 Active
I just.. am stuck. Why can it not find "AddInfrastructureData"?
Try to add a using namespace where the AddInfrastructureData resides.
Replace Travel.Data with the appropriate namespace from your code:
namespace Travel.Data;
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddInfrastructureData(this IServiceCollection servicesCollection)
{
//...
return servicesCollection;
}
}
// Startup.cs
using Travel.Data;
If the extension method is located in a different project or package add it via right clicking the Dependencies submenu of the project and select "Add Project Reference..." or "Manage NuGet Packages...".
Please provide more info in case that it was not helpful. Is the AddInfrastructureData your own method or an external one etc?
you could check your guide book if you have missed any packages
and you could check your guide book if you have missed to copy the codes like below:
public static class DependencyInjection
{
public static IServiceCollection AddInfrastructureData(this IServiceCollection services)
{
return services;
}
public static IServiceCollection AddInfrastructureShared(this IServiceCollection services,IConfiguration configuration)
{
return services;
}
}
I'm new to ASP .NET Core, however I've had coded ASP .NET before, now I am following this tutorial
"https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-5.0&tabs=visual-studio-code".
I am using Visual Studio Code.
I'm doing the "Scaffold a controller" section.
When I run the last dotnet statement, stated in that section, I get the error that I refer on the title (same error that shows on my problems tab inside the terminal).
Problem is, that the error can be resolved by inserting a "using" statement, as it's shown on the section "Register the database context".
I have followed thoroughly all the steps, but when it comes to using TodoApi.Models, I get the error
Type or namespace name 'Models' does not exist in namespace 'TodoApi' (assembly reference missing?) [TodoApi]
I have read many threads but none seem to answer the question regarding my specific case, here I'll show some of my code so you can compare mine with the Tutorial's
My Startup.cs file:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.EntityFrameworkCore;
using TodoApi.Models;
namespace TodoApi
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddDbContext<TodoContext>(opt => opt.UseInMemoryDatabase("TodoList"));
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.ResponseCompression;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using OfflineEventManagment.Data;
using OfflineEventManagment.Areas;
using System;
using System.Collections.Generic;
using System.IO.Compression;
using System.Linq;
using System.Threading.Tasks;
namespace OfflineEventManagment
{
public class Startup
{
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.AddDbContext<UserContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = false)
.AddEntityFrameworkStores<UserContext>();
services.AddControllersWithViews();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.Use(async (ctx, next) =>
{
await next();
if (ctx.Response.StatusCode == 404 && !ctx.Response.HasStarted)
{
//Re-execute the request so the user gets the error page
string originalPath = ctx.Request.Path.Value;
ctx.Items["originalPath"] = originalPath;
ctx.Request.Path = "/Error/_404";
await next();
}
});
if (env.IsDevelopment())
{
//Error
app.UseMigrationsEndPoint();
app.UseDeveloperExceptionPage();
}
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.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
}
}
Here is The Image
**Can anyone help me solve this? I can't figure why there is such an error, if this error cant be solved, can asp.net core identity code can be removed? if so, how?
entitycore identity cannot create context file, also I cann't see database file for this particular project only!
**Or Should I create New Project?
I recreated a project and encountered the same error as you, as follows:
Then I introduced the package to solve the problem: (Pay attention to the .net version you are using)
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore
Resutl:
For more information, please refer to this article: https://learn.microsoft.com/en-us/aspnet/core/migration/31-to-50?view=aspnetcore-5.0&tabs=visual-studio#usedatabaseerrorpage-obsolete
app.UseMigrationsEndPoint();
It's under the Library below. try this.
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore
I get an error when I build my project 'The type or namespace name 'VegaDbContext' could not be found (are you missing a using directive or an assembly reference?)'. I am following a tutorial using vs code editor. This is what I have in my "Startup" class:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SpaServices.AngularCli;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using VegaDbContext;
namespace aspcoreangular
{
public class Startup
{
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.AddDbContext<VegaDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Default")));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
// In production, the Angular files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
// To learn more about options for serving an Angular SPA from ASP.NET Core,
// see https://go.microsoft.com/fwlink/?linkid=864501
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
}
}
}
and this is my dbcontext:
using Microsoft.EntityFrameworkCore;
namespace aspcoreangular.persistence
{
public class VegaDbContext : DbContext
{
public VegaDbContext(DbContextOptions<VegaDbContext> options) : base(options)
{ }
}
}
One thing I have noticed as well, in vs code, I do not get red lines if there is an error in my code. That's the reason maybe that I do not see the errors in it. Can you please help me with this.
Replace
using VegaDbContext;
with
using aspcoreangular.persistence;
You are referencing the VegaDbContext context in your Using Directive , and not the namespace it belongs to
Further reading
using Directive (C# Reference)
I'm trying to use Quartz sheduker in my asp core 2.0 project.
I downloaded Quartz 3.0.4 using nuget and after that i added services.AddQuartz(new QuartezOptions {});
to ConfigureService function in Startup.cs
I also have the same problem with app.UseQuartz()
Thats, how Startup.cs is looking now:
using AspProj.Map;
using Microsoft.Extensions.Configuration;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Swashbuckle.AspNetCore.Swagger;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Quartz;
namespace AspProj
{
public class Startup
{
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.AddDbContext<CacheDbContext>(opt => opt.UseSqlServer(Configuration.GetConnectionString("DB")));
services.AddScoped<CacheDbContext>();
services.AddMvc();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "API", Version = "v1" });
});
services.AddQuartz(new QuartezOptions { });
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "DbApi V1");
});
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
app.UseQuartz();
}
}
}
I tried to connect different Quartz namespaces through using, but it has no use.
I just keep getting "IServiceCollection does not contain definition for AddQuartz" from visual studio 2017.
error screenshot
I cant find any information about someone with the same problem as me.
Did sombody knows, how can i fix this?
Try to add the Quartz namespace in your dependencies and this should work:
using Quartz;
Also ensure that the proper package has been installed:
dotnet add package Quartz.Extensions.Hosting
need to install package Quartz.NET Microsoft.Extensions.DependencyInjection