I'm trying to create a Stock Tracking System with ASP.NET MVC and I created a database with SQL Server but I can't connect this from my app.
When I try to start. VS is giving me this error can anyone help me?
Here are my Program.cs and DBContext.cs files
Program.cs:
using Microsoft.EntityFrameworkCore;
using stockTrackingSystem.Data;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
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.UseRouting();
app.UseAuthorization();
//DB CONNECTION
var connectionString = builder.Configuration.GetConnectionString("AppDb");
builder.Services.AddDbContext<DBContext>(x => x.UseSqlServer(connectionString));
DBContext.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.EntityFrameworkCore;
using stockTrackingSystem.Models;
namespace stockTrackingSystem.Data
{
public class DBContext: DbContext
{
public DbSet<Store> Store { get; set; }
public DbSet<Category> Category { get; set; }
public DbSet<Customer> Customer { get; set; }
}
}
Modify your DBContext class to include a constractor.
public class DBContext: DbContext
{
public DBContext(DbContextOptions<DBContext> options)
: base(options)
{
}
public DbSet<Store> Store { get; set; }
public DbSet<Category> Category { get; set; }
public DbSet<Customer> Customer { get; set; }
}
Related
I'm building an ASP.NET Web Api with simple CRUD operations and a Database which should be generated using EF Code First and Migrations.
In terms of the structure of the project, I am using ASP.NET Web API as the main project and a class library as the database context.
This is what I have in my Class library:
Database Context:
using Microsoft.EntityFrameworkCore;
using MyApp.Database.Models;
namespace MyApp.Database.Context;
public class MyAppContext : DbContext
{
public MyAppContext(DbContextOptions<MyAppContext> options) : base(options) { }
public virtual DbSet<Booking> Bookings { get; set; }
public virtual DbSet<Person> Persons { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Seed();
base.OnModelCreating(modelBuilder);
}
}
Database Models:
namespace MyApp.Database.Models;
public class Booking
{
public int Id { get; set; }
public int Week { get; set; }
public int DayOfWeek { get; set; }
public int Hour { get; set; }
public int PersonId { get; set; }
public virtual Person Person { get; set; }
}
using System.Collections.Generic;
namespace MyApp.Database.Models;
public class Person
{
public int Id { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public int Age { get; set; }
public virtual IEnumerable<Booking> Bookings { get; set; }
}
Besides that I have a class in the library called SeederExtension which has an Extension method that should Seed the database
using Microsoft.EntityFrameworkCore;
using MyApp.Database.Models;
namespace MyApp.Database;
public static class SeedExtension
{
public static void Seed(this ModelBuilder modelBuilder)
{
modelBuilder.Entity<Person>().HasData(new Person
{
Id = 1,
Firstname = "John",
Lastname = "Doe",
Age = 28,
});
}
}
In my ASP.NET Web API project I register the Database context in my Program.cs with the following code.
builder.Services.AddDbContext<MyAppContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("MyAppDb"));
});
The problem is now when I want to add migrations. I go to the Package Manager Console and navigate to the Class Library project where my Database Context is located.
Then I enter this command to add a migration:
dotnet ef migrations add "Init"
which produces this error then:
Unable to create an object of type 'MyAppContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
I've seen a lot of tutorial where this worked but unfortunately after hours of research I haven't found a working solution.
I'm using .net6 and the following NuGet packages in my class library
Microsoft.EntityFrameworkCore (version 7.0.2)
Microsoft.EntityFrameworkCore.SqlServer (version 7.0.2)
Microsoft.EntityFrameworkCor.Tools (version 7.0.2)
And here is my connectionString if it helps:
{
"ConnectionStrings": {
"MyAppDb": "server=(LocalDB)\\mssqllocaldb;database=MyAppDB;integrated security=True"
}
}
Try adding a parameterless constructor: public MyAppContext() {}.
Options are to pass to constructor by DI based on your ConfigureService in the Startup class. 'Add migration' shouldn't know what options to pass since it does not use the Startup.
If you take a look at here
https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/projects?tabs=dotnet-core-cli
Note the difference in your command and selecting the database csproj. In the docs it has:
dotnet ef migrations add NewMigration --project WebApplication1.Migrations
The connection string comes from your main project. Again, from the docs:
services.AddDbContext<ApplicationDbContext>(
options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection"),
x => x.MigrationsAssembly("WebApplication1.Migrations")));
I have, obviously, just pasted in the above from the docs. You will need to match with your own projects.
If you instead run the migrations using just the database project, I am not sure it would pick up the connection string out the web api project.
I get this error:
InvalidOperationException: No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.
I tried everything, but right again. I want to define the startup connection string, but I can not.
My ApplicationDbContext is:
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(){}
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options): base(options){}
public DbSet<Course> Courses { get; set; }
public DbSet<CourseType> CourseTypes { get; set; }
public DbSet<CourseState> CourseStates { get; set; }
public DbSet<Topic> Topics { get; set; }
public DbSet<Heding> Hedings { get; set; }
}
My StartUp is :
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DbLearning"))));
}
My appSetting.json is :
"ConnectionStrings": {
"DbLearning": "Server=(localdb)\\mssqllocaldb;Database=DbLearning;Trusted_Connection=True;"
}
The problem is that in startUp but in onConfiguring not problem
You can use the most known way using localdb
Code in appsetting.json
"ConnectionStrings": {
"DbLearning": "Server=(localdb)\\mssqllocaldb;Database=DbLearning;Trusted_Connection=True;"
}
Code in Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DbLearning")));
}
"ConnectionStrings": {
"DbLearning": "Server=(localdb)\\mssqllocaldb;Database=DbLearning;Trusted_Connection=True;"
}
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DbLearning")));
}
I'm relatively new to using mvc, I have created an application with several models with scaffold controllers and CRUD views. When running my application on visual studio's local host and localdb my application works perfectly, however when trying to deploy my application I am receiving an error,
error processing your request
on the pages associated with my models.
I have deployed my project on a production iis server, and have setup a user login and database on an ms sql server. My project has the correct connection string to interact with the sql server, however when observing the database, my tables associated with my projects models are not being created - which is the route cause of the errors I am receiving.
Is anyone able to suggest why my tables are not being created; below are examples of my code, please note I am also using the asp.net Identity functionality, these tables are also not being created:
Example of one of my models:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace newwebsite.Models
{
public class Store
{
public int ID { get; set; }
public string ItemName { get; set; }
public string ItemImageName { get; set; }
public decimal ItemPrice { get; set; }
public string ItemDescription { get; set; }
public string ItemFeatures { get; set; }
}
public class StoreDBContext : DbContext
{
public DbSet<Store> Blog { get; set; }
public StoreDBContext()
: base("DefaultConnection")
{
}
public static StoreDBContext Create()
{
return new StoreDBContext();
}
}
}
Example of my connection string:
<add name="DefaultConnection" connectionString="Data Source='MSSqlServerIP'; Initial Catalog=NewWebsite2017; User ID=NewWebsite2017; Password=*****" providerName="System.Data.SqlClient" />
When I've deployed my project all views are working which suggests my controllers for these views are fine. I'm purely getting the error wherever data from the database is supposed to be shown. I believe these errors are due to my tables not being created, but am unsure why this is.
Update
I have edited the model (and others in accordingly) as follows, however still have no luck.
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace newwebsite.Models
{
public class Store
{
public int ID { get; set; }
public string ItemName { get; set; }
public string ItemImageName { get; set; }
public decimal ItemPrice { get; set; }
public string ItemDescription { get; set; }
public string ItemFeatures { get; set; }
}
public class StoreDBContext : DbContext
{
public DbSet<Store> Blog { get; set; }
public StoreDBContext()
: base("DefaultConnection")
{
Database.SetInitializer<StoreDBContext>(new CreateDatabaseIfNotExists<StoreDBContext>());
}
}
}
Specify a DB initializer in your DB context
public StoreDBContext()
: base("DefaultConnection")
{
Database.SetInitializer<StoreDBContext>(new CreateDatabaseIfNotExists<StoreDBContext>());
}
There are several other initializers. e.g. DropCreateDatabaseIfModelChanges or DropCreateDatabaseAlways (be careful. this can delete your data) or you can program your own initializer.
This question already has answers here:
The entity type 'Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>' requires a key to be defined
(4 answers)
Closed 4 years ago.
I have the following ApplicationDbContext class:
using EsportshubApi.Models.Entities;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace EsportshubApi.Models
{
public class ApplicationDbContext : IdentityDbContext<Account>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
public ApplicationDbContext() {}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}
}
}
Account class looks like so:
using System;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
namespace EsportshubApi.Models.Entities
{
public class Account : IdentityUser
{
private Account() { }
public static AccountBuilder Builder()
{
return new AccountBuilder(new Account());
}
public string AccountId { get; set; }
public Guid AccountGuid { get; set; }
public string Salt { get; set; }
public bool Verified { get; set; }
public string Checksum { get; set; }
public string Password { get; set; }
public DateTime Created { get; set; }
public DateTime Updated { get; set; }
}
}
In my Startup.cs inside of the method ConfigureServices i run:
services.AddIdentity<Account, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
app.UseIdentity();
And inside of the Startup.cs Configure method i run:
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
serviceScope.ServiceProvider.GetService<EsportshubContext>().Database.Migrate();
serviceScope.ServiceProvider.GetService<ApplicationDbContext>().Database.Migrate();
serviceScope.ServiceProvider.GetService<EsportshubContext>().EnsureSeedData();
}
}
app.UseIdentity();
And when running my application with a development environment, i get this error:
The entity type 'IdentityUserLogin<string>' requires a primary key to be defined.
In my world IdentityUserLogin is a system class, and everything i do is "allowed" so it boggles me how this can ever give an error. I have read about this issue in similar posts, but usually they need to add the OnModelCreating base.OnModelCreating call, which i have. Does anyone have a suggestion??
Thanks.
Edit:
Even if i simplify it to this:
using EsportshubApi.Models.Entities;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace EsportshubApi.Models
{
public class ApplicationDbContext : IdentityDbContext<IdentityUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
public ApplicationDbContext() {}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<IdentityUserLogin<string>>().HasKey(iul => iul.UserId);
modelBuilder.Entity<IdentityRole>().HasKey(r => r.Id);
modelBuilder.Entity<IdentityUserRole<string>>().HasKey(r => new { r.RoleId, r.UserId });
}
}
}
Where i just give it IdentityUser directly it doesn't work
The reason for the failure is that the lack of base.OnModelCreating(), which is in the method OnModelCreating called by the dbcontext class.
Decorate AccountGuid (if this is your primary key) with Key attribute so EF knows this is a primary key as below:
[Key]
public Guid AccountGuid { get; set; }
it's been a while since I work with EntityDataModel. I used to do things like:
var listaProductos = dbContext.Productos.Select(p => new
I just started a new web project with asp.net and added the entity data model but If i try to do the same as the example above I can't use ".Select". Do I need to install any Nuget package or something?
I work with Visual Studio 2013.
Thanks for your help.
You should add namespase to your file:
using System.Linq;
check your namespace and dbContext class.
Like
using ContosoUniversity.Models;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace ContosoUniversity.DAL
{
public class SchoolContext : DbContext
{
public SchoolContext() : base("SchoolContext")
{
}
public DbSet<Student> Students { get; set; }
public DbSet<Enrollment> Enrollments { get; set; }
public DbSet<Course> Courses { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
}