3

I have 3 different tables and 3 different columns which are primary columns.

 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)

or

_context.Teacher(x=>x.TeacherId == someValue)

or

_context.Lesson(x=>x.TeacherId == someValue)

only changing table name and key value.

What is the best way using generic method?

D-Shih
  • 44,943
  • 6
  • 31
  • 51

2 Answers2

0

Make a general repository and than inherit it with native repository of each class like this

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>
    {



    }

Make a object of native repositry and call the function

Where ever you need to call the function make a object of student repository

StudentRepositoy repository = new StudentRepositoy();
var result = repository.SelectByID(3);
Faizan
  • 542
  • 5
  • 16
0

You can consider to use a pattern like "generic repository". Or you can simply write a method takes Expression> as input and pass the expression to it.

https://code.msdn.microsoft.com/generic-repository-pattern-ddea2262

https://www.codeproject.com/Articles/814768/CRUD-Operations-Using-the-Generic-Repository-Patte

Emre Savcı
  • 3,034
  • 2
  • 16
  • 25