Error message:
No DbContext was found in assembly 'API_Test_Console'. Ensure that you're using the correct assembly and that the type is neither abstract nor generic.
If you take a look at projects structure:
Project "API_Test_Console" Should be responsible only for create new instances os objects and running this solution
Project "API_Test_Library" Contains all classes that will be used for this solution. Also the classes responsibles for connecting with SQL.
API_Test_Library -> SYSTEM_CONECTION.CS (where DBContext is currently set)
using API_Test_Library.Models;
using Microsoft.EntityFrameworkCore;
namespace API_Test_Library.DB;
public class SYSTEM_CONTEXT : DbContext
{
public DbSet<Value> Values { get; set; }
public DbSet<Category> Categories { get; set; }
private string ConnectionString = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=API_Test_V0;Integrated Security=True;Connect Timeout=30;Encrypt=False;Trust Server Certificate=False;Application Intent=ReadWrite;Multi Subnet Failover=False";
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(ConnectionString);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Value>()
.HasKey(a => a.Id);
modelBuilder.Entity<Value>()
.HasOne(a => a.Category);
modelBuilder.Entity<Category>()
.HasKey(a => a.Id);
modelBuilder.Entity<Category>()
.HasMany(a => a.Values);
base.OnModelCreating(modelBuilder);
}
}
Fix I know so far
Create another class at API_Test_Console -> Console_Context.CS. Like that:
Code
using API_Test_Library.Models;
using Microsoft.EntityFrameworkCore;
namespace API_Test_Console;
public class Console_CONTEXT : DbContext
{
public DbSet<Value> Values { get; set; }
private string ConnectionString = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=API_Test_V0;Integrated Security=True;Connect Timeout=30;Encrypt=False;Trust Server Certificate=False;Application Intent=ReadWrite;Multi Subnet Failover=False";
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(ConnectionString);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Value>()
.HasKey(a => a.Id);
base.OnModelCreating(modelBuilder);
}
}
Question:
Is there another way of fixing it? Or is mandatory to have a DBContext set for each project?
Note: Projects references are set like:
To have only one DBContext set for the enrity SOLUTION.
To add migrations to a project containing your DbContext
class, you need to select the project from the Package Manager Console's dropdown. Choose Api_Test_Library.
By the way, what's up with the weird naming? SYSTEM_CONTEXT
? SYSTEM_CONECTION
?