1

I m new in .net core 2.1

I m working with .net core 2.1 with code first approach

issue is when I create a new object dbcontext class then give error see below line

dbcontextstudent db=new dbcontextstudent();  //here give an red line

appsettings.json

 },
  "ConnectionStrings": {
    "sqlserverconn": "Server=DEVISSHAHID; Database=studdbs; User id=xxxx;Password=xxxxx;"
  },

Startup.cs

 public void ConfigureServices(IServiceCollection services)
        {
            //connection string
            services.AddDbContext<DbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("sqlserverconn")));

student.cs

namespace WebApplication1.Models
{
    public class student
    {
        [Key]
        public int studid { get; set; }

        public string studname { get; set; }

        public string studsalary { get; set; }

        public int studage { get; set; }
    }
}

dbcontextstudent.cs

namespace WebApplication1.Models
{
    public class dbcontextstudent : DbContext
    {
        public dbcontextstudent(DbContextOptions<dbcontextstudent> options) : base(options)
        {

        }

        public DbSet<student> stud { get; set; }
    }
}

HomeController.cs

enter image description here

I m not understood the above intellisense

I write the code as per intellisense but still give an error I know error is clear but not solved

which place doing I m wrong?

1 Answer 1

1

You will have to pass your DbContext type to the AddDbContext method in ConfigureServices method like this:

            services.AddDbContext<dbcontextstudent>(options => options.UseSqlServer(Configuration.GetConnectionString("sqlserverconn")));

After that, you have registered the dbcontextstudent class in dependency injection.

You shouldn't create the instance of dbcontextstudent on your own like you did:

dbcontextstudent db=new dbcontextstudent();

Instead you can inject it though the constructor of your controller like this:

public HomeController : Controller 
{
   private readonly dbcontextstudent _db;

   public HomeController(dbcontextstudent db)
   {
     _db = db;
    }

... and then you can use the _db variable in your post action
}
Sign up to request clarification or add additional context in comments.

5 Comments

still I facing dbcontext error i.sstatic.net/j7P3c.png
I updated my answer, both the HomeController and ConfgureServices needs adjustments
please can u help more i m facing one error i.sstatic.net/fY9Fs.png please help
can you start a new question for this? it's a separate issue
error is solved just add this line in context class Database.EnsureCreated(); thanks for your time

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.