I have a solution with the following two projects:
- Razor Class Library
- ASP.NET Core web application
In the class library I have a dbcontext like this:
public partial class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string> { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } public DbSet<Customer> Customers { get; set; } } In the web application I register the dbcontext as a service using the following lines in my Startup.cs file
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer( Configuration.GetConnectionString("ApplicationDbContextConnection"))); At this point I can use the dbcontext in both projects. Now, without changing the class library I want to define new tables for the same database so I created a new dbcontext in the web application project which inherits from the one that I have in the class library.
public class ExtendedApplicationDbContext : ApplicationDbContext { public ExtendedApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } public DbSet<Product> Products { get; set; } } I update my Startup.cs file so that I will register the new dbcontext as well so that I will be able to use the Products table in the web application.
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer( Configuration.GetConnectionString("ApplicationDbContextConnection"))); services.AddDbContext<ExtendedApplicationDbContext>(options => options.UseSqlServer( Configuration.GetConnectionString("ApplicationDbContextConnection"))); Now I can use ApplicationDbContext in both projects but when I try to use the ExtendedApplicationDbContext in the web application, something strange happens.
I can read the data but all the changes that I make do not update the database.
I try to explain it but I can not find a way to solve the problem. Can someone help me understand what is wrong with my code?
SaveChanges/await SaveChangesAsyncon the right context? Can you show the code where you make the changes?