Home > Enterprise >  StudentDbContext is null using Asp.net Core Web api
StudentDbContext is null using Asp.net Core Web api

Time:12-29

am a beginner in ASP.NET Core. I am creating a Web API service. While I am fetching the data from the database, I had a problem. What is the error I got? I have successfully done the database migration part and created the database successfully. StudentDbContext is null

StudentController

namespace webb.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class StudentController : ControllerBase
    {
        private StudentDbContext studentDbContext;


        public StudentController(StudentDbContext studentDbContext)
        {
            studentDbContext = studentDbContext;
        }

        // GET: api/<EmployeeController>
        [HttpGet]
        public IEnumerable<Student> Get()
        {
           // var studens = studentDbContext.Student;
            return studentDbContext.Student;
           
        }


    }
}

Model

    public class Student
    {
        public int id { get; set; }
        public string stname { get; set; }

        public string course { get; set; }
    }
}

StudentDbContext

public class StudentDbContext : DbContext
{
    public StudentDbContext(DbContextOptions<StudentDbContext> options) : base(options)
    {
    }
    public DbSet<Student> Student { get; set; }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("Data Source=.;Initial Catalog=ams;Integrated Security=True; TrustServerCertificate = True");
    }
}

IDataService

  public interface IDataService<T>
    {
        Task<IEnumerable<T>> GetAll();
        Task<T> Get(int id);
        Task<T> Create(T entity);
        Task<bool> Delete(T entity);
        Task<T> Update(T entity);
    }
}

CodePudding user response:

I have successfully done the database migration part and created the database successfully. StudentDbContext is null

Well, two mistake has been done. Your model has no enter image description here

For further details you can have a look on official document here.

  • Related