I'm trying to publish a code-first webapp that uses sqlite to Azure. Now, the application is working fine locally. but when I publish, it seems that the database file is not being created properly, and I get the following error:
SqliteException: SQLite Error 1: 'no such table: Blogs'.
Microsoft.Data.Sqlite.Interop.MarshalEx.ThrowExceptionForRC(int rc, Sqlite3Handle db)
I am not sure as to why the Blogs table isn't created (and I assume the rest aren't created either).
my ApplicationDbContext.cs looks like this:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public ApplicationDbContext()
{
Database.EnsureCreated();
Database.Migrate();
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}
public DbSet<Publication> Publications { get; set; }
public DbSet<Blog> Blogs { get; set; }
public DbSet<Student> Students { get; set; }
public DbSet<ApplicationUser> ApplicationUser { get; set; }
}
Configuration:
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlite(Configuration.GetConnectionString("DefaultConnection"))
);
}
and DefaultConnection in appsettings.json:
"ConnectionStrings": {
"DefaultConnection": "Filename=.\\mydb.sqlite"
},
Furthermore, when I download mydb.sqlite and open it, its completely empty.
#Tseng your instinct about EnsureCreated was right. I ended up solving this by clearing the constructor and adding this to the end of the Configure method in Startup.cs
var serviceScopeFactory = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>()
using (var serviceScope = serviceScopeFactory.CreateScope())
{
var dbContext = serviceScope.ServiceProvider.GetService<ApplicationDbContext>();
dbContext.Database.EnsureCreated();
}
I found the answer here
Related
I am trying to rekindle this topic. It was once started over 10 years ago, and while there were some comments that are a couple years ago, it has now been closed. Yet again, this still is kind of unclear to me.
A lot of people put their opinions on it, and whilist there were some good reasons and opinions, the practical approach, and overall conclusion is still unclear, at least to me.
My situation: I am trying to create a way more complicated than neccesary app to research and test things. I've been using only one DbContext up until now and now I wish to separate it by creating a new one for identity/security (I am aware that IdentityDbContext exists, and while this is a smarter solution, I wanna play around).
As I managed to configure the second DbContext and create a migration, the migration state has been resetted to "Initial" and new tables are created (instead of using the old ones).
My question: What is a good practical example where introduction of the new DbContext is applied and how to replicate the up until now Migration Snapshot to it (in order to continue the sequence). Also, to replicate the future state of Migration Snapshot to the original DbContext and so on.
Here are some code examples that I managed to scribble:
This is a part of the base class extension for DbContexts.
public class DbContextExtend : DbContext
{
protected readonly ICurrentUserService _userService;
protected readonly IDateTime _dateTime;
public DbContextExtend(DbContextOptions<ReservationDbContext> options) : base(options) { }
public DbContextExtend(DbContextOptions<ReservationDbContext> options,
IDateTime datetime,
ICurrentUserService userService) : base(options)
{
_dateTime = datetime;
_userService = userService;
}
public DbContextExtend(DbContextOptions<SecurityDbContext> options) : base(options) { }
public DbContextExtend(DbContextOptions<SecurityDbContext> options,
IDateTime datetime,
ICurrentUserService userService) : base(options)
{
_dateTime = datetime;
_userService = userService;
}
public DbSet<Audit> Audits { get; set; }
public async override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
{
//var auditEntries = await OnBeforeSaveChangesAsync();
var result = await base.SaveChangesAsync(cancellationToken);
//await OnAfterSaveChanges(auditEntries);
return result;
}
}
A freshly introduced DbContext - OnModelCreating, Ignore Reservations and everything after it in order to focus on the 3 tables of importance (is there a better way to do this).
public class SecurityDbContext : DbContextExtend, ISecurityDbContext
{
public SecurityDbContext(DbContextOptions<SecurityDbContext> options) : base(options) { }
public SecurityDbContext(DbContextOptions<SecurityDbContext> options,
IDateTime datetime,
ICurrentUserService userService) : base(options, datetime, userService) { }
public DbSet<User> Users { get; set; }
public DbSet<LoginDetails> LoginDetails { get; set; }
public DbSet<Role> Roles { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.ApplyConfiguration(new Configurations.SecurityConfiguration.RoleConfiguration());
modelBuilder.ApplyConfiguration(new Configurations.SecurityConfiguration.UserConfiguration());
modelBuilder.ApplyConfiguration(new Configurations.SecurityConfiguration.LoginDetailsConfiguration());
modelBuilder.Ignore<Reservation>();
}
}
The DbContext that was in use up untill now. Ignoring the table that should be out of it, the LoginDetails.
public class ReservationDbContext : DbContextExtend, IReservationDbContext
{
public ReservationDbContext(DbContextOptions<ReservationDbContext> options) : base(options) { }
public ReservationDbContext(DbContextOptions<ReservationDbContext> options,
IDateTime datetime,
ICurrentUserService userService) : base(options, datetime, userService) { }
public DbSet<Role> Roles { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<LoginDetails> LoginDetails { get; set; }
public DbSet<EventType> EventTypes { get; set; }
public DbSet<Event> Events { get; set; }
public DbSet<Question> Questions { get; set; }
public DbSet<EventQuestion> EventQuestions { get; set; }
public DbSet<EventOccurrence> EventOccurrences { get; set; }
public DbSet<Ticket> Tickets { get; set; }
public DbSet<Reservation> Reservations { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.ApplyConfiguration(new EventTypeConfiguration());
modelBuilder.ApplyConfiguration(new EventConfiguration());
modelBuilder.ApplyConfiguration(new QuestionConfiguration());
modelBuilder.ApplyConfiguration(new EventOccuranceConfiguration());
modelBuilder.ApplyConfiguration(new ReservationConfiguration());
modelBuilder.ApplyConfiguration(new TicketConfiguration());
modelBuilder.ApplyConfiguration(new UserConfiguration());
modelBuilder.ApplyConfiguration(new RoleConfiguration());
modelBuilder.Ignore<LoginDetails>();
}
}
UserConfiguration - an example of a configuration and it is a table that separates both contexts (but is contained in both).
public class UserConfiguration : AuditableEntityConfiguration<User>
{
public override void ConfigureAuditableEntity(EntityTypeBuilder<User> builder)
{
builder.HasKey(u => u.Id);
builder.Property(u => u.Email)
.HasMaxLength(128)
.IsRequired();
builder.Property(u => u.Name)
.IsRequired();
builder.Property(u => u.PhoneNumber)
.HasMaxLength(20)
.IsRequired(false);;
builder.Property(u => u.RoleId)
.IsRequired();
builder.HasOne(u => u.Role)
.WithMany(r => r.Users)
.HasForeignKey(u => u.RoleId);
builder.HasOne(u => u.LoginDetails)
.WithOne(ld => ld.User)
.HasForeignKey<LoginDetails>(u => u.UserId)
.IsRequired();
}
}
It might be worth noting that I also decided to separated SecurityDbContext logic to a different project.
Please feel free to give me all advice and real world experience that you can. I would greatly appreciate it!
You should generate different migration for each DbContext. If you have different entities that you want to be in the same db table, explicitly say that in each configuration, using the ToTable() method. Also, their configuration should match. Finally, you should also be explicit about the db name, so in each OnModelCreating you should pass in the builder.HasDefaultScheme() the same value.
Let's say i have an IdentityDbContext that inherits from the IdentityDbContext<>, the default that you get in asp, but with an AppUser that inherits from the IdentityUser, so i have a configuration for that. Then i would have something like that:
public class IdentityDbContext : IdentityDbContext<AppUser>
{
//Other stuff
protected override void OnModelCreating(ModelBuilder builder)
{
builder.HasDefaultSchema("TestDb");
builder.ApplyConfiguration(new AppUserConfiguration())
base.OnModelCreating(builder);
}
}
Then i have a WriteDbContext that inherits from the DbContext, and i have a configuration for a customer:
public class WriteDbContext : DbContext
{
public DbSet<Customer> Customers { get; set; }
//Other stuff
protected override void OnModelCreating(ModelBuilder builder)
{
builder.HasDefaultSchema("TestDb");
builder.ApplyConfiguration(new CustomerConfiguration())
base.OnModelCreating(builder);
}
}
At that point i need to generate a migration for each DbContext and then apply them. Then i would have all the identity stuff and the customer in the same Database.
I could also have a CustomerReadModel that i can use only for reads, so it does not have any logic, private fields and maybe has navigation to other ReadModels. As long as they all have the same configuration, for example the FirstName in both of them is configured to be nvarchar(50), if the customer has one Address (as an entity), then the CustomerReadModel has also one or it has a AddressReadModel configured as the Address etc, and in both configuration i have builder.ToTable("Customers") the will both point to the same customers db table:
public class ReadDbContext: DbContext
{
public DbSet<CustomerReadModel> Customers{ get; set; }
//Other stuff
protected override void OnModelCreating(ModelBuilder builder)
{
builder.HasDefaultSchema("TestDb");
builder.ApplyConfiguration(new CustomerReadModelConfiguration())
base.OnModelCreating(builder);
}
}
And i now should not add a migration for the ReadDbContext, since the database is already configured.
You can also check these out if you want (disclaimer: they are mine):
https://www.youtube.com/watch?v=QkHfBNPvLms
https://www.youtube.com/watch?v=MNtXz4WvclQ
Edit : I made a demo some time ago that has some of the above: https://github.com/spyroskatsios/MakeYourBusinessGreen
i had an application where data is saved in different sql schema for different Users.
For e.g.
User 1 Data is saved in SCHEMA1
User 2 Data is saved in SCHEMA2
Previously application was developed in MVC 3 and it is working fine and as expected.
Now we are migrating application in .Net Core 2.2 in which this fucntionality is not working
.net core does not have IDbModelCacheKeyProvider due to this only one schema is working
Below is the DBContext File
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
//public string Schema { get; set; }
private readonly IConfiguration configuration;
public string SchemaName { get; set; }
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public ApplicationDbContext(string schemaname)
: base()
{
SchemaName = schemaname;
}
public DbSet<EmployeeDetail> EmployeeDetail { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
var configuration = builder.Build();
optionsBuilder.UseSqlServer(configuration["ConnectionStrings:SchemaDBConnection"]);
var serviceProvider = new ServiceCollection().AddEntityFrameworkSqlServer()
.AddTransient<IModelCustomizer, SchemaContextCustomize>()
.BuildServiceProvider();
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.RemovePluralizingTableNameConvention();
modelBuilder.HasDefaultSchema(SchemaName);
base.OnModelCreating(modelBuilder);
}
public string CacheKey
{
get { return SchemaName; }
}
}
public class SchemaContextCustomize : ModelCustomizer
{
public SchemaContextCustomize(ModelCustomizerDependencies dependencies)
: base(dependencies)
{
}
public override void Customize(ModelBuilder modelBuilder, DbContext dbContext)
{
base.Customize(modelBuilder, dbContext);
string schemaName = (dbContext as ApplicationDbContext).SchemaName;
(dbContext as ApplicationDbContext).SchemaName = schemaName;
}
}
My question is how to change schemaName at runtime
So what is the right way to organize that mechanism:
Figure out the schema name by the user credentials;
Get user-specific data from database from specific schema.
I was able to change schema at runtime by changing onConfiguring Method
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public string SchemaName { get; set; }
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public ApplicationDbContext(string schemaname)
: base()
{
SchemaName = schemaname;
}
public DbSet<EmployeeDetail> EmployeeDetail { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
var configuration = builder.Build();
var serviceProvider = new ServiceCollection().AddEntityFrameworkSqlServer()
.AddSingleton<IModelCustomizer, SchemaContextCustomize>()
.BuildServiceProvider();
optionsBuilder.UseSqlServer(configuration["ConnectionStrings:SchemaDBConnection"]).UseInternalServiceProvider(serviceProvider);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// modelBuilder.MapProduct(SchemaName);
modelBuilder.RemovePluralizingTableNameConvention();
if (!string.IsNullOrEmpty(SchemaName))
{
modelBuilder.HasDefaultSchema(SchemaName);
}
base.OnModelCreating(modelBuilder);
}
public string CacheKey
{
get { return SchemaName; }
}
public class SchemaContextCustomize : ModelCustomizer
{
public SchemaContextCustomize(ModelCustomizerDependencies dependencies)
: base(dependencies)
{
}
public override void Customize(ModelBuilder modelBuilder, DbContext dbContext)
{
base.Customize(modelBuilder, dbContext);
string schemaName = (dbContext as ApplicationDbContext).SchemaName;
(dbContext as ApplicationDbContext).SchemaName = schemaName;
}
}
}
The best way is to use Multi-Tenancy Architecture to be able to use database schema per user ( Tenant )
This architecture is recommended for Saas appllications
Concepts
Let’s agree on some basic concepts:
We use a tenant identification (or resolution) strategy to find out what tenant are we talking to
A tenant DbContext access strategy will figure out the way to retrieve (and store)
This article will show you how to implement Multi-tenancy app using .net core : https://stackify.com/writing-multitenant-asp-net-core-applications/
I'm working on my first application in .Net Core.
I'm getting this build error for some reason:
Error CS7036 There is no argument given that corresponds to the required formal parameter 'options' of 'LakeViewContext.LakeViewContext(DbContextOptions<LakeViewContext>)' LakeView
I wasn't able to find a solution through Google Search or MS documentation.
My Context class:
using LakeView.Models;
using Microsoft.EntityFrameworkCore;
namespace LakeView
{
public class LakeViewContext : DbContext
{
public LakeViewContext(DbContextOptions<LakeViewContext> options) : base(options)
{
}
public DbSet<HTMLElement> HTMLElements { get; set; }
public DbSet<CustomizedElement> CustomizedElements { get; set; }
public DbSet<TemplateFileType> TemplateFileTypes { get; set; }
public DbSet<StyleFile> StyleFiles { get; set; }
public DbSet<Template> Templates { get; set; }
public DbSet<Course> Courses { get; set; }
public DbSet<Page> Pages { get; set; }
public DbSet<HTML> HTMLs { get; set; }
public DbSet<Comment> Comments { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<CustomizedElementTemplate>()
.HasKey(s => new { s.CustomizedElementId, s.TemplateId });
base.OnModelCreating(modelBuilder);
}
}
}
Controller class:
using LakeView.Models;
using LakeView.Models.ViewModels;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
namespace LakeView.Controllers
{
public class CoursesController : Controller
{
private LakeViewContext db = new LakeViewContext();
public IActionResult Index()
{
ICollection<Course> courses = db.Courses.ToList();
return View(courses);
}
[HttpGet]
public IActionResult CreateCourse()
{
return View("CreateCourse");
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult CreateCourse(CreateCourseViewModel courseVM)
{
if (ModelState.IsValid)
{
Course newCourse = new Course()
{
CourseCode = courseVM.CourseCode,
CourseTitle = courseVM.CourseTitle,
MasterOU = int.Parse(courseVM.MasterOU)
};
db.Courses.Add(newCourse);
db.SaveChanges();
return RedirectToAction("Index");
}
return View("CreateCourse", courseVM);
}
}
}
(bold text is underlined in Visual Studio with the same error
"private LakeViewContext db = new LakeViewContext();"
Startup class:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using LakeView.Models;
namespace LakeView
{
public class Startup
{
// 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 https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
var connection = #"Data Source = (localdb)\MSSQLLocalDB; Database = LakeViewData; Trusted_Connection = True;";
services.AddDbContext<LakeViewContext>(options => options.UseSqlServer(connection));
}
// 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();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
}
}
}
LakeViewContext expects a DbContextOptions<LakeViewContext> to be passed into its constructor. However, you are calling the constructor without providing anything:
private LakeViewContext db = new LakeViewContext();
To fix the issue, you can just plug into the Dependency Injection system that you've set up. To do this, change your controller as follows:
public class CoursesController : Controller
{
private readonly LakeViewContext db;
public CoursesController(LakeVieContext db)
{
this.db = db;
}
...
The ASP.NET Core Dependency Injection system will provide you with a LakeViewContext in the constructor - Just use that.
you are trying to new up the dbcontext in your controller without passing in the options.
You should instead add a constructor to your controller and add the dbContext to your constructor so it will get injected, ie
public CoursesController(LakeViewContext dbContext)
{
db = dbContext;
}
private LakeViewContext db;
... the rest of your code
dependency injection will pass it in to you
When observing at how the classes are generated via the database first approach, I was able to fix this error with an empty constructor.
public class MyDBContext : DbContext
{
public MyDBContext()
{
}
//Rest of your code
}
I am working on simple MVC 6 app with .NET Core 1.0 and trying to read data from database using Entity Framework Core 1.0 and getting following error in my LINQ query from where I am trying to read table; The LINQ query is in HomeController class
Error
An unhandled exception occurred while processing the request.
SqlException: Invalid object name 'TestModel'.
Model Class
[Table("TestTable")]
public class TestModel
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
}
TestDbContext
public class TestDbContext: DbContext
{
public TestDbContext(DbContextOptions<TestDbContext> options): base(options)
{ }
public DbSet<TestModel> TestModels { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<TestModel>().ToTable("TestModel");
}
}
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddApplicationInsightsTelemetry(Configuration);
services.AddDbContext<TestDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("UCASAppDatabase")));
services.AddMvc();
}
project.json
"Microsoft.EntityFrameworkCore.SqlServer": "1.0.1",
"Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final",
"System.ComponentModel.Annotations": "4.1.0"
appsettings.json
{
"ApplicationInsights": {
"InstrumentationKey": ""
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
},
"ConnectionStrings": {
"UCASAppDatabase": "Data Source=mydb;Initial Catalog=UCAS-DB;Integrated Security=True;Persist Security Info=True"
}
}
HomeController (trying to read table here!)
public class HomeController : Controller
{
private readonly TestDbContext _context;
public HomeController(TestDbContext context)
{
this._context = context;
}
public IActionResult About()
{
var query = (from b in _context.TestModels
select b).ToList();
ViewData["Message"] = "Your application description page.";
return View();
}
Not sure what I missing here!
My Fault found error, was giving wrong table name in override OnModelCreating
public class TestDbContext: DbContext
{
public TestDbContext(DbContextOptions<TestDbContext> options): base(options)
{ }
public DbSet<TestModel> TestModels { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<TestModel>().ToTable("TestTable");
}
}
Long story, originally a project was started using Azure AD auth as the authentication for the application, approaching the end of the project we noticed the huge flaws Azure auth had (Normal Users where not able to authenticate)
So the decision was made to move from Azure auth to ASP Identity Auth. To do this a new web project was created and all of the data from the first project was placed into it by coping the files from one project to another.
This caused a few headaches but eventually got everything going. With the new project it came with a Migration and ApplicationDBContext already to handle all of the ASP tables. This was the first issue as we already had a very detailed DbContext but using command line we managed to run all the migrations correctly.
Now we are presented with a new issue, every time we launch the application in VS2015 the error:
The Error:
InvalidOperationException: Unable to resolve service for type 'Musted.Models.ApplicationDbContext' while attempting to activate 'Microsoft.AspNet.Identity.EntityFramework.UserStore`3[Musted.Models.ApplicationUser,Microsoft.AspNet.Identity.EntityFramework.IdentityRole,Musted.Models.ApplicationDbContext]'.
I believe the issue is somewhere in the Startup.cs with how the identity is created.
Existing Context: ProjectContext.cs
New ASP Auth Context: ApplicationDBContext.cs
Startup.cs <-> Where I believe the issue to be
public void ConfigureServices(IServiceCollection services)
{
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<ProjectContext>();
services.AddScoped<ProjectContextSeedData>();
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddMvc();
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, MusteredContextSeedData seeder)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
try
{
using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>()
.CreateScope())
{
serviceScope.ServiceProvider.GetService<ApplicationDbContext>()
.Database.Migrate();
}
}
catch { }
}
app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear());
app.UseStaticFiles();
app.UseIdentity();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
ApplicationDBContext.cs
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var connString = Startup.Configuration["Data:ProjectContextConnection"];
optionsBuilder.UseSqlServer(connString);
base.OnConfiguring(optionsBuilder);
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}
}
}
ProjectContext.cs
public class ProjectContext: DbContext
{
public ProjectContext()
{
Database.EnsureCreated();
}
public DbSet<User> Users {get; set;}
public DbSet<UserLevel> UserLevels { get; set; }
public DbSet<ApprovalStatus> ApprovalStatus { get; set; }
public DbSet<Area> Areas { get; set; }
public DbSet<Company> Company { get; set; }
public DbSet<Event> Events { get; set; }
public DbSet<LeaveType> LeaveTypes { get; set; }
public DbSet<Leave> Leave { get; set; }
public DbSet<Shift> Shifts { get; set; }
public DbSet<UserLoginAudit> UserLoginAudit { get; set; }
public DbSet<UserType> UserType { get; set; }
public DbSet<ShiftDay> ShiftDay { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var connString = Startup.Configuration["Data:ProjectContextConnection"];
optionsBuilder.UseSqlServer(connString);
base.OnConfiguring(optionsBuilder);
}
}
UPDATE
So after some more digging, I have found the line in the ASP generated code that is failing.
private readonly UserManager<ApplicationUser> _userManager;
//This is the line that is erroring
var result = await _userManager.CreateAsync(user, model.Password);
That calls is all throughout the ASP stuff so I am guessing nothing will work
In the end - I deleted the project and imported the classes from the start. I wasted hours trying to get it working the other way and the new project was just much quicker.