I created a class library which is going to have my database model with DB first approach. I am using the Northwind database.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<NorthwindContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("NorthwindContext"));
});
}
In this method in asp.net project it tells me that the NorthwindContext
is not convertible to DBcontext
but the class inherits from it:
Error CS0311
The type 'NorthwindDal.NorthwindContext' cannot be used as type parameter 'TContext' in the generic type or method 'EntityFrameworkServiceCollectionExtensions.AddDbContext(IServiceCollection, Action?, ServiceLifetime, ServiceLifetime)'.
There is no implicit reference conversion from 'NorthwindDal.NorthwindContext' to 'Microsoft.EntityFrameworkCore.DbContext'.
If I don't use the AddDbcontext
and try to run the project, it just tells me that it cannot find the connection string for the database.
The context is auto created and it inherits from the DBcontext
as well.
I think its probably because I try to use the class library to do this but is there a way to use class library with ASP.NET?
Northwind Context
public partial class NorthwindContext : DbContext
{
public NorthwindContext()
: base("name=NorthwindContext")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<Category> Categories { get; set; }
public virtual DbSet<CustomerDemographic> CustomerDemographics { get; set; }
public virtual DbSet<Customer> Customers { get; set; }
public virtual DbSet<Employee> Employees { get; set; }
public virtual DbSet<Order_Detail> Order_Details { get; set; }
public virtual DbSet<Order> Orders { get; set; }
public virtual DbSet<Product> Products { get; set; }
public virtual DbSet<Region> Regions { get; set; }
public virtual DbSet<Shipper> Shippers { get; set; }
public virtual DbSet<Supplier> Suppliers { get; set; }
public virtual DbSet<Territory> Territories { get; set; }
}
CodePudding user response:
Based on your scenario if you would like to implement
database first approach
you could follow the below steps
Database Schema:
CodePudding user response:
To generate model classes and database context from an existing database you need to use ef tool scaffolding. You can do it using the command
dotnet ef dbcontext scaffold "Your connection string" Microsoft.EntityFrameworkCore.SqlServer
You need the add reference following NuGet packages if you need to run the command.
dotnet add package Microsoft.EntityFrameworkCore.Design dotnet add package Microsoft.EntityFrameworkCore.SqlServer