Home > front end >  Unable to create an object of type 'MyContext'. For the different patterns supported at de
Unable to create an object of type 'MyContext'. For the different patterns supported at de

Time:08-24

Model :

using System.ComponentModel.DataAnnotations;
using System;

namespace Data
{
public class User
{
    [Key]
    public int UserID { get; set; }
    public string? Username { get; set; }
    public User()
    {
        
    }
}
}

Context :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.SqlClient;
using System.Data;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Design;

namespace Data
{
public class MyContext : DbContext
{
    public DbSet<User>? Users { get; set; }
    public MyContext(DbContextOptions<MyContext> options) : base(options) { }
    public MyContext()
    {
    }
 }
}

Connection string :

"ConnectionStrings": {
"MyContext" : "data source =(LocalDb)\\MSSQLLocalDB;Initial Catalog=TestVsCodeDB;               Integrated Security=True ",
"providerName" :"System.Data.SqlClient"
}

Slo

I use VS Code and I get this error during migration. I used a similar method in asp.net mvc, but I get this error in asp.net core

CodePudding user response:

Have you added you dbContext in startup or program.cs ? Are you doing the migration in the correct path? it should be something like this:

cd ./project_with_migrations_folder
dotnet ef --startup-project ../my_startup_project_path/ migrations add myMigration01

CodePudding user response:

You must use the default constructor of MyContext.cs. Remove

public MyContext(DbContextOptions<MyContext> options) : base(options) { }

In Program.cs do this

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
string ConnectionString = configuration.GetConnectionString("MyContext");
    services.AddDbContext<ApplicationDbContext>(
        options => options.UseSqlServer(ConnectionString));
}
  • Related