dimanche 1 janvier 2023

How can I use reflection with varying classes?

What I'm trying to achieve here is that I want to insert data into a database from file using a CRUD class with type . I'm gonna demonstrate a simple example of the situation.

public class SubjectTester<T>where T : class
    {
        public void Create()
        {
            var db_context = new DbContext();
            //here I get file content and do stuff with it
            //here I want create an instance of T and add the data from the file
            //here I will use the Add method from my DbContext and save the changes
        }
    }
    public class DbContext 
    {
        //has some stuff
    }
    public class TestSubjectA
    {
        //some properties
        public int Id { get; set; }
        public string Name { get; set; }
    }
    public class TestSubjectB
    {
        //some properties
        public double Sum { get; set; }
    }
    public class TestSubjectC
    {
        //some properties
        public int Id { get; set; }
        public string Name { get; set; }
        public bool IsRigged { get; set; }
    }

As you can see the problem is that some tables have more columns than others and also the data types are different aswell. I'm doing this because I want to dynamically add data depending on the class that I get. Also I don't want to have a bunch of if elses to check what is the type of T... I hope I was clear in my explanation.





Aucun commentaire:

Enregistrer un commentaire