EF .Net Core达到Controller的类

时间:2019-04-06 11:52:52

标签: c# entity-framework asp.net-core asp.net-core-mvc

我有.net核心项目,想将db与ef连接。下面的代码是我的数据库上下文。

public class YTContext:DbContext
    {
        public YTContext(DbContextOptions<YTContext> options) : base(options) { }

        //protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        //{
        //    optionsBuilder.UseMySql(@"Server=localhost;Database=kariyer_portal;Uid=root;Pwd=1234;");
        //}
        public DbSet<Student> Students { get; set; }

        public DbSet<University> Universities { get; set; }

        public DbSet<Bolum> Bolums { get; set; }

        public DbSet<Admin> Admins { get; set; }

        public DbSet<Announcement> Announcements { get; set; }
    }

在Startup.class中,我编写了连接。


public void ConfigureServices(IServiceCollection services)
        {

            services.AddSingleton<ITest, MyConfig>();
            services.AddMvc();
            services.AddMvc().AddJsonOptions( options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore );


            services.AddDbContext<YTContext>(options => options.UseMySql(Configuration.GetConnectionString("MySqlCon")));

        }

在我的存储库类中,我写在下面。

public class StudentRepository
    {
        private readonly YTContext _db;
        public StudentRepository(YTContext context)
        {
            _db = context;
        }

        public  List<Student> GetStudents(int page, int limit = 8, string query = null)
        {
            try
            {
                var skip = (page - 1) * limit;
                var students = _db.Students.Where(x => query == null || x.Name.Contains(query) || x.Surname.Contains(query) || x.University.Name.Contains(query) || x.Bolum.Name.Contains(query))
                    .Include(x=>x.Bolum).Include(x=>x.University)
                    .Skip(skip).Take(limit).ToList();
                return students;
            }
            catch (Exception ex)
            {
                return null;
            }

        }
    }

我的问题是我无法从代码下面的控制器到达此类。


 public class StudentController : Controller
    {

        public StudentRepository repo;
        [HttpGet]
        public IActionResult List()
        {
            var students = repo.GetStudents(1, 6,null);
            return View(students);
        }

        [HttpPost]
        public IActionResult Paginate(Paginate paginate)
        {
            var students = repo.GetStudents(paginate.page, paginate.limit,paginate.query);
            return Json(new {status = 200, student = students});
        }
    }
public StudentRepository repo;

上面的代码在控制器中返回null。我该如何从控制器上这一节课?

1 个答案:

答案 0 :(得分:3)

您需要在Startup的DI容器中注册它:

services.AddScoped<StudentRepository, StudentRepository>();

然后将其注入到控制器的构造函数中:

public StudentController(StudentRepository studentRepo) {
    repo = studentRepo;
}