I am developing application in Core 2.0 and using identity to create tables. So when I run application the database automatically create. Later when I try to run migration command it does not create table.
//DAL
public class ApplicationDbContext:IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options):base(options)
{
}
public DbSet<tblContact> tblContacts { get; set; }
//protected override void OnModelCreating(ModelBuilder builder)
//{
// base.OnModelCreating(builder);
//}
}
//Required Table Class
public partial class tblContact
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ContactId { get; set; }
public string PhoneNumber { get; set; }
}
Following is commands that I ran
add-migration 20180921
update-database -verbose
At the end of output in console it says
Error Number:2714,State:6,Class:16
There is already an object named 'AspNetRoles' in the database.
One more thing that when I drop database and run application then required tables create automatically without running any command.
What I am missing here?
Following is Start.cs file
public class Startup
{
public Startup(IConfiguration configuration, IHostingEnvironment env)
{
Configuration = configuration;
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
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.AddMvc();
services.AddDbContext<ApplicationDbContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
});
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.ConfigureApplicationCookie(config =>
{
// Cookie settings
config.ExpireTimeSpan = TimeSpan.FromHours(2);
config.SlidingExpiration = true;
config.LoginPath = "/Account/Login";
config.LogoutPath = "/Account/LogOut";
config.AccessDeniedPath = "/Account/AccessDenied";
});
services.AddTransient<IAccountBAL, AccountBAL>();
services.AddSingleton<IConfiguration>(Configuration);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IAccountBAL _iAccountBAL)
{
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
SeedDatabase.Initialize(app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope().ServiceProvider);
_iAccountBAL.CreateDefaultRoles().Wait();
_iAccountBAL.CreateSuperAdmin().Wait();
}
}
public static void Initialize(IServiceProvider serviceProvider)
{
var context = serviceProvider.GetRequiredService<ApplicationDbContext>();
var userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
context.Database.EnsureCreated();
}
Sounds like your application applying migrations when it is running. Please check your Startup.cs has migration. You need to remove it if your application has it in order to run migration from package manager console.
private static void InitializeMigrations(IApplicationBuilder app)
{
using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
MyDbContext dbContext = serviceScope.ServiceProvider.GetRequiredService<MyDbContext>();
dbContext.Database.Migrate();
}
}
From MSDN
Ensures that the database for the context exists. If it exists, no action is taken. If it does not exist then the database and all its schema are created. If the database exists, then no effort is made to ensure it is compatible with the model for this context.
Note that this API does not use migrations to create the database. In addition, the database that is created cannot be later updated using migrations. If you are targeting a relational database and using migrations, you can use the DbContext.Database.Migrate() method to ensure the database is created and all migrations are applied.
Related
I am working on a .NET Core 3.1 application. I have a requirement where i have to inject a service in Startup.cs. My code is:
Program.cs:
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices(servicesCollection =>
{
servicesCollection.AddScoped<IUnauthorizedAccessService, UnauthorizedAccessService>();
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
Startup.cs:
public Startup(IConfiguration configuration, IUnauthorizedAccessService unauthorizedAccessService)
{
Configuration = configuration;
_unauthorizedAccessService = unauthorizedAccessService;
}
public IConfiguration Configuration { get; }
public IUnauthorizedAccessService _unauthorizedAccessService { get; set; }
When i run the code, i get the following exception:
Unable to resolve service for type 'Interface.Service.IUnauthorizedAccessService' while attempting to activate 'Website.Startup'.'
How can i inject the service in Startup.cs ? I have even tried it getting in Configure method. But then, i get the exception at repository level. Code:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IUnauthorizedAccessService unauthorizedAccessService)
{
_unauthorizedAccessService = unauthorizedAccessService;
if (env.IsDevelopment())
{
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.UseSession();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseCookiePolicy(new CookiePolicyOptions
{
MinimumSameSitePolicy = SameSiteMode.Strict,
});
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=User}/{action=Index}/{id?}");
});
}
I have a method RegisterDatabase which is being called from ConfigureServices. Code:
private void RegisterDatabase(IServiceCollection services)
{
services.AddDbContext<TrainingContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
Service code is:
public class UnauthorizedAccessService : IUnauthorizedAccessService
{
private readonly IEventLogRepository _eventLogRepository;
public UnauthorizedAccessService(IEventLogRepository eventLogRepository)
{
_eventLogRepository = eventLogRepository;
}
public async Task<BaseResponse> LogUnauthorizedAccessInDB(string user, string url, string sessionId)
{
try
{
EventLog eventLog = new EventLog();
eventLog.Httpsession = sessionId;
eventLog.AppUserName = user;
eventLog.EventDateTime = DateTime.Now;
eventLog.MessageLevel = 3;
eventLog.Message = url;
await _eventLogRepository.Add(eventLog);
}
catch(Exception ex)
{
}
return HelperService.Response(null, null);
}
}
When Adding the object, i get the exception
Cannot access a disposed context instance. A common cause of this error is disposing a context instance that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling 'Dispose' on the context instance, or wrapping it in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.
Object name: 'TrainingContext'.
All of my other repositories are working but, getting exception only at this point. What can be the possible issue ? Any help would be much appreciated.
Basically, what i am trying to achieve is that i want to log unauthorized access to my site in Database. Code is:
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(o =>
{
o.AccessDeniedPath = "/Home/Error";
o.LoginPath = "/Login";
o.SlidingExpiration = false;
o.Events = new CookieAuthenticationEvents
{
//OnRedirectToAccessDenied = new Func<RedirectContext<CookieAuthenticationOptions>, Task>(context =>
OnRedirectToAccessDenied = new Func<RedirectContext<CookieAuthenticationOptions>, Task>(test)
};
});
test method is:
private async Task<Task> test (RedirectContext<CookieAuthenticationOptions> context)
{
string user = context.HttpContext.User.Identity.Name;
string url = "/" + context.Request.Host.Value + "/" + context.Request.RouteValues["controller"] + "/" + context.Request.RouteValues["action"];
string sessionId = context.HttpContext.Session.Id;
await _unauthorizedAccessService.LogUnauthorizedAccessInDB(user, url, sessionId);
context.Response.Redirect("/Home/Error");
return context.Response.CompleteAsync();
}
You need to create a scoped object that implements CookieAuthenticationEvents. For example:
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using System.Threading.Tasks;
namespace MyApplication.Services
{
public class MyCookieAuthenticationEvents : CookieAuthenticationEvents
{
private readonly IUnauthorizedAccessService _unauthorizedAccessService;
public MyCookieAuthenticationEvents(
IUnauthorizedAccessService unauthorizedAccessService)
{
_unauthorizedAccessService = unauthorizedAccessService;
}
public override Task RedirectToAccessDenied(
RedirectContext<CookieAuthenticationOptions> context)
{
// TODO: you can use _unauthorizedAccessService here
return base.RedirectToAccessDenied(context);
}
}
}
To inject this, you'd do it as so:
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.EventsType = typeof(MyCookieAuthenticationEvents);
});
services.AddScoped<MyCookieAuthenticationEvents>();
services.AddScoped<IUnauthorizedAccessService, UnauthorizedAccessService>();
Make sure you remove that IUnauthorizedAccessService from your program.cs. You don't inject there. You inject in your Configure method.
This is how you do proper dependency injection. You don't do what the accepted answer is doing. That is probably one of the most unorthodox things I have ever seen in a long time.
Startup.cs is designed for configuring own services and pipeline configuration. You can not inject your custom services in constructor just because they are not configured yet.
Docs:
The host provides services that are available to the Startup class
constructor. The app adds additional services via ConfigureServices.
Both the host and app services are available in Configure and
throughout the app.
i wqant ot use the autofac in my project .
i write this startup :
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 IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddControllers();
var builder = new ContainerBuilder();
builder.RegisterAssemblyTypes(Assembly.GetEntryAssembly())
.AsImplementedInterfaces();
builder.Populate(services);
builder.AddDispatchers();
var conteiner = builder.Build();
return new AutofacServiceProvider(conteiner);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
nad this is my program.cs :
public class Program
{
public static void Main(string[] args)
{
var host = Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureWebHostDefaults(webHostBuilder =>
{
webHostBuilder
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>();
})
.Build();
host.Run();
}
}
but it show me this errro :
'ConfigureServices returning an System.IServiceProvider isn't supported.'
How can is solve this problem?
This is because you are trying the pre 3.0 way. Check the ConfigureServices docs. It does not supprot the IServiceProvider return type.
public virtual void ConfigureServices (Microsoft.Extensions.DependencyInjection.IServiceCollection services);
From the autofac docs:
This is not for ASP.NET Core 3+ or the .NET Core 3+ generic hosting support - ASP.NET Core 3 has deprecated the ability to return a service provider from ConfigureServices
Check Autofac net core guide post 3.0
public class Program
{
public static void Main(string[] args)
{
// ASP.NET Core 3.0+:
// The UseServiceProviderFactory call attaches the
// Autofac provider to the generic hosting mechanism.
var host = Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureWebHostDefaults(webHostBuilder => {
webHostBuilder
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>();
})
.Build();
host.Run();
}
}
public class Startup
{
public Startup(IHostingEnvironment env)
{
// In ASP.NET Core 3.0 `env` will be an IWebHostingEnvironment, not IHostingEnvironment.
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
this.Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; private set; }
public ILifetimeScope AutofacContainer { get; private set; }
// ConfigureServices is where you register dependencies. This gets
// called by the runtime before the ConfigureContainer method, below.
public void ConfigureServices(IServiceCollection services)
{
// Add services to the collection. Don't build or return
// any IServiceProvider or the ConfigureContainer method
// won't get called.
services.AddOptions();
}
// ConfigureContainer is where you can register things directly
// with Autofac. This runs after ConfigureServices so the things
// here will override registrations made in ConfigureServices.
// Don't build the container; that gets done for you by the factory.
public void ConfigureContainer(ContainerBuilder builder)
{
// Register your own things directly with Autofac, like:
builder.RegisterModule(new MyApplicationModule());
}
// Configure is where you add middleware. This is called after
// ConfigureContainer. You can use IApplicationBuilder.ApplicationServices
// here if you need to resolve things from the container.
public void Configure(
IApplicationBuilder app,
ILoggerFactory loggerFactory)
{
// If, for some reason, you need a reference to the built container, you
// can use the convenience extension method GetAutofacRoot.
this.AutofacContainer = app.ApplicationServices.GetAutofacRoot();
loggerFactory.AddConsole(this.Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseMvc();
}
}
I'm trying to configure NHibernate on .net core but still no sucess.
I can read the data, but when I try to save or delete, it doesn't work.
There is too much information like how I created my services, repository and mapping, so I will skip some files in this question, but everything is avaliable at my git repo.
So I have a very simple model.
public class Book
{
public virtual Guid Id { get; set; }
public virtual string Title { get; set; }
}
I also created a extension method for adding nhibernate in my service
public static class NHibernateExtensions
{
public static IServiceCollection AddNHibernate(this IServiceCollection services, string connectionString)
{
var mapper = new ModelMapper();
mapper.AddMappings(typeof(NHibernateExtensions).Assembly.ExportedTypes);
HbmMapping domainMapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
var configuration = new Configuration()
.DataBaseIntegration(c =>
{
c.Dialect<MsSql2012Dialect>();
c.ConnectionString = connectionString;
c.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
c.SchemaAction = SchemaAutoAction.Validate;
c.LogFormattedSql = true;
c.LogSqlInConsole = true;
});
configuration.AddMapping(domainMapping);
var fluentSessionFactory = Fluently
.Configure(configuration)
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<Book>())
.BuildSessionFactory();
var sessionFactory = configuration.BuildSessionFactory();
services.AddSingleton(fluentSessionFactory);
services.AddScoped(factory => fluentSessionFactory.OpenSession());
services.AddScoped<ISessionManager, SessionManager>();
return services;
}
}
Here is my StartUp
public void ConfigureServices(IServiceCollection services)
{
var connStr = Configuration.GetConnectionString("DefaultConnection");
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddSingleton<WeatherForecastService>();
services.AddNHibernate(connStr);
services.AddTransient<IBookRepository, BookRepository>();
services.AddTransient<IBookService, BookService>();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
And I created a BaseRepository for handle simple repository actions.
The problem I'm having is that in BaseRepository, when I call Add, it doesn't persists in the database.
public void Delete(T entity){
using (var transaction = Session.BeginTransaction())
{
Session.Delete(entity);
transaction.Commit();
Session.Flush();
}
}
When I call Queryable.ToList(), I get everything as expected.
What I'm doing wrong on the configurations that it doesn't persists in the db?
Observation: The database is SQL Server 2017 and is running on a docker container.
That's because you open new session on each Session access:
protected ISession Session => SessionFactory.OpenSession();
Transaction is started in one session add/delete in other flush in third. Obviously you need to do all operations in one session.
Also you don't need to call Flush by default - it should be called automatically on transaction.Commit. And if you really need to call Flush - do it before transaction commit.
First of all, I'm trying to seed my database with sample data. I have read that this is the way to do it (in Startup.Configure) (please, see ASP.NET Core RC2 Seed Database)
I'm using ASP.NET Core 2.0 with the default options.
As usual, I register my DbContext in ConfigureServices.
But after that, in the Startup.Configure method, when I try to resolve it using GetRequiredService, it throws with this message:
System.InvalidOperationException: 'Cannot resolve scoped service
'SGDTP.Infrastructure.Context.SGDTPContext' from root
provider.'
My Startup class like this:
public abstract class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<SGDTPContext>(options => options.UseInMemoryDatabase("MyDatabase"))
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
SeedDatabase(app);
}
private static void SeedDatabase(IApplicationBuilder app)
{
using (var context = app.ApplicationServices.GetRequiredService<SGDTPContext>())
{
// Seed the Database
//...
}
}
}
What am I doing wrong?
Also, is this the best place to create seed data?
You're registering SGDTPContext as a scoped service and then attempting to access it outside of a scope. To create a scope inside your SeedDatabase method, use the following:
using (var serviceScope = app.ApplicationServices.CreateScope())
{
var context = serviceScope.ServiceProvider.GetService<SGDTPContext>();
// Seed the database.
}
Credit to #khellang for pointing out the CreateScope extension method in the comments and to #Tseng's comment and answer re how to implement seeding in EF Core 2.
Was getting this error while following the official ASP.Net MVC Core tutorial, in the section where you are supposed to add seeded data to your application. Long story short, adding these two lines
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
to the SeedData class solved it for me:
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;
namespace MvcMovie.Models
{
public static class SeedData
{
public static void Initialize(IServiceProvider serviceProvider)
{
using (var context = new MvcMovieContext(
serviceProvider.GetRequiredService<DbContextOptions<MvcMovieContext>>()))
{
// Look for any movies.
if (context.Movie.Any())
{
return; // DB has been seeded
}
...
Can't tell you the WHY, but these were two of the options I got from following the Alt + Enter quick fix option.
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)
{
var key = Encoding.ASCII.GetBytes(Configuration.GetSection("AppSettings:Token").Value);
services.AddDbContext<DataContext>(x => x.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")).EnableSensitiveDataLogging());
services.AddMvc();
services.AddTransient<Seed>();
services.AddCors();
services.AddScoped<IAuthRepository, AuthRepository>();
services.AddScoped<IUserRepository, UserRepository>();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(Options =>
{
Options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
}
);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env ,Seed seeder)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler(builder =>
{
builder.Run(async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
var error = context.Features.Get<IExceptionHandlerFeature>();
if (error != null)
{
context.Response.AddApplicationError(error.Error.Message);
await context.Response.WriteAsync(error.Error.Message).ConfigureAwait(false);
}
});
});
}
seeder.SeedUser();
app.UseCors(x=>x.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().AllowCredentials());
app.UseMvc();
}
}
}
I've got an Asp.Net 5 web application which use EF7 and SQL Server 2014. Now I need to make second DBContext which will connect to SQL Server 2008 R2. For some reason I'm able to connect but not able to get any data from database.
config.json:
"Data": {
"PMSConnectionString": "Data Source=xxxx;User ID=xxxx;Password=xxxx;Initial Catalog=xxxx;",
"MTOCL2ConnectionString": "Server=xxxx;Database=xxxx;User Id=xxxx;Password=xxxx;"
}
Startup.cs:
public Startup(IHostingEnvironment env)
{
// Setup configuration sources.
var configurationBuilder = new ConfigurationBuilder()
.AddJsonFile("config.json")
.AddEnvironmentVariables();
Configuration = configurationBuilder.Build();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver =
new CamelCasePropertyNamesContractResolver();
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});
services.AddCaching(); // Adds a default in-memory implementation of IDistributedCache
services.AddSession(s => s.IdleTimeout = TimeSpan.FromMinutes(360));
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<MTOCL2Context>(options =>
options.UseSqlServer(Configuration["Data:MTOCL2ConnectionString"])
).AddDbContext<PMSContext>(options =>
options.UseSqlServer(Configuration["Data:PMSConnectionString"]))
;
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.MinimumLevel = LogLevel.Information;
loggerFactory.AddConsole();
loggerFactory.AddDebug();
app.Use(async (context, next) =>
{
context.Response.Headers.Append("Cache-Control", "private, no-store");
await next();
});
app.UseSession();
app.UseIISPlatformHandler();
app.UseStaticFiles();
app.UseMvc();
}
MTOCL2Context.cs:
public class MTOCL2Context:DbContext
{
public DbSet<SubLotPriority> SubLotPriorities { get; set; }
}
UserController:
[Route("api/[controller]")]
public class UsersController : Controller
{
private readonly PMSContext _dbContext;
private readonly MTOCL2Context _dbContext2;
public UsersController(MTOCL2Context dbContext2, PMSContext dbContext)
{
_dbContext2 = dbContext2;
_dbContext = dbContext;
}
}
When I run application and try to get data from SubLotPriority, I get error:
Evaluation of method System.Linq.SystemCore_EnumerableDebugView'1[[SublotPriority...
I actually don't get any error, when I go into dbcontext I don't get any results and error message appear on the screen. Don't know how to get full message: