【发布时间】:2020-08-15 17:15:52
【问题描述】:
AppDbContext.cs
using Microsoft.EntityFrameworkCore;
namespace EduManSystems.Model
{
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options)
: base(options)
{
}
public DbSet<Course> Courses { get; set; }
public DbSet<Student> Student_master { get; set; }
}
}
IStudentRepository.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EduManSystems.Model
{
public interface IStudentRepository
{
Student GetStudent(string id);
IEnumerable<Student> GetStudents();
//Student GetStudents();
Student Add(Student student);
}
}
SqlStudentRepository.cs
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Data.Common;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace EduManSystems.Model
{
public class SqlStudentRepository : IStudentRepository
{
private readonly AppDbContext context;
public SqlStudentRepository(AppDbContext context)
{
this.context = context;
}
public Student GetStudent(string id)
{
return context.Student_master.Find(id);
}
public IEnumerable<Student> GetStudents()
{
return context.Student_master.FromSql("select * from student_master").ToList();
}
}
}
StudentController.cs
using EduManSystems.Model;
using EduManSystems.ViewModel;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace EduManSystems.Controllers
{
public class StudentController : Controller
{
private readonly IStudentRepository _studentRepository;
private readonly IHostingEnvironment hostingEnvironment;
public StudentController(IStudentRepository studentRepository,
IHostingEnvironment hostingEnvironment)
{
_studentRepository = studentRepository;
this.hostingEnvironment = hostingEnvironment;
}
[HttpGet]
public ViewResult Index()
{
var model = _studentRepository.GetStudents();
return View(model);
}
[HttpGet]
public JsonResult StudentList()
{
var model = _studentRepository.GetStudents();
return Json(model);
}
}
}
我试过这个,但我得到了这样的错误,
大家好,
我需要你的帮助。在这里,它从 SQL 服务器(原始 sql 查询或 Linq)中检索所有数据。但是,我只需要特定的列,例如 select stud_first_name,stud_last_name from student_master;
SQL 查询必须返回表的所有列。例如context.Student_Master.FromSql("Select Stud_First_Name, Stud_Last_Name from Student_Master).ToList() 会抛出异常。
请帮帮我
谢谢,
【问题讨论】:
-
你也可以添加
Student类代码。
标签: c# sql asp.net-mvc linq