我有 3 个不同的表和 3 个不同的列,它们是主列。
public class Student
{
public int StudentId { get; set; }
public string Name { get; set; }
}
public class Teacher
{
public int TeacherId { get; set; }
public string Name { get; set; }
}
public class Lesson
{
public int LessonId { get; set; }
public string Name { get; set; }
}
var _context = new MyContext()
_context.Student(x=>x.StudentId == someValue)
或
_context.Teacher(x=>x.TeacherId == someValue)
或
_context.Lesson(x=>x.TeacherId == someValue)
只改变表名和键值。
使用泛型方法的最佳方式是什么?
最佳答案
创建一个通用存储库,而不是像这样用每个类的本地存储库继承它
public class GeneralRepository<T> where T : class
{
private MyContext Context = new MyContext();
protected DbSet<T> Dbset { get; set; }
public GeneralRepository()
{
Dbset = Context.Set<T>();
}
public T SelectByID(int? id)
{
var Record = Dbset.Find(id);
return (Record);
}
public class StudentRepositoy :GeneralRepository<Student>
{
}
创建一个本地存储库的对象并调用函数
在需要调用函数的地方创建学生存储库的对象
StudentRepositoy repository = new StudentRepositoy();
var result = repository.SelectByID(3);
关于c# - 如何使用 LINQ 在 db 上下文中为 3 个不同的表在 asp .net mvc 中编写通用查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49705988/