0

Ok, I have 3 classes: Teacher, Student and Database for that matter. I wanna read data from database and put it in Teacher or Student. So i have to write something like this:

public Teacher dbSelect(string Table="Teacher")
{
    Table = char.ToUpper(Table[0]) + Table.Substring(1);
    string query = "SELECT * FROM " + Table + ";";
    return dbConnect(query, true);
}

But i must have this exact Method with Student return:

public Student dbSelect(string Table="Student")
{
    Table = char.ToUpper(Table[0]) + Table.Substring(1);
    string query = "SELECT * FROM " + Table + ";";
    return dbConnect(query, true);
}

Now I can write each one in their ViewModel, But I want to put them in Database class. So is there any way to do that?
(I know i can return them in a list and then work with that list, But just wanna know if there is a way or not!)

UPDATE: I forgot to put dbConnect in here, so:

public List<Teacher> dbConnect(string query)
    {
        SQLiteConnection conn = null;
        SQLiteCommand command = null;
        SQLiteDataReader reader = null;
        Teacher result = new Teacher(null, null, null, null, null, null, null, null);
            //    try
            {
                conn = new SQLiteConnection(db.db);
                conn.Open();
                command = new SQLiteCommand(query, conn);
                reader = command.ExecuteReader();
            }
            //   catch (Exception ex) { }
            while (reader.Read())
            {
                Teacher temp = new Teacher(
                    reader[0].ToString(),    
                    reader[1].ToString(),                              
                    reader[2].ToString(),                              
                    reader[3].ToString(),                              
                    reader[4].ToString(), 
                    reader[5].ToString(),                              
                    reader[6].ToString(),                              
                    reader[7].ToString()                               
                    );
                result.Items.Add(temp);
            }
        conn.Close();
        return result.Items;
    }

And again the exact thing exist for Student but returning:

public List<Student> dbConnect(string query)
{
    ...
}  

Answer: I had a Base class and of course wanted to return a List with a specific type, So I used @Jauch answer, but with returning the List.

5
  • Hi @Mostafa. A few thoughts. 1. Both routines will return the exactly same value, that is the value returned by dbConnect. 2. What is the relationship between the probably READER that will be returned by cbConnect and Student/Teacher?
    – Jauch
    Aug 21, 2016 at 14:27
  • Hello @Jauch. One of the return Student, and another one return Teacher. Actually that's what i had to put in my question! :D. I'll be fixing it right now!
    – Mostafa
    Aug 21, 2016 at 14:36
  • Ah... Much clearer now :)
    – Jauch
    Aug 21, 2016 at 14:43
  • I did something similar, but I used a system based on generics and interfaces. In order to "populate" the object (Teacher or Student, for example), that can have different columns/properties, I used reflection to match the columns in the reader with the properties in the object.
    – Jauch
    Aug 21, 2016 at 14:48
  • If you could give me an example, It would be great. Because I don't know how they work. Thanks a lot.
    – Mostafa
    Aug 21, 2016 at 14:54

2 Answers 2

0

Here is an idea on how to do what you want, adapted from a code of mine:

public class BaseClass<T> 
    where T : new ()
{
    protected List<object> list;
    protected string query;
    protected PropertyInfo[] fProperties;
    protected Assembly fStoreAssembly;

    public BaseClass()
    {
        list = new List<T>();
        fStoreAssembly = Assembly.GetAssembly (typeof(T));
        fProperties = typeof(T).GetProperties();
    }

    public void Read()
    {
        SQLiteConnection conn = null;
        SQLiteCommand command = null;
        SQLiteDataReader reader = null;

        try
        {
            conn = new SQLiteConnection(db.db);
            conn.Open();
            command = new SQLiteCommand(query, conn);
            reader = command.ExecuteReader();

            StoreResults (reader);

            conn.Close();
        }
        catch (Exception ex) 
        {
            //deal with the exception here
        }
    }

    //Store results walks through all the records returned and 
    //creates new instances of the store object and saves in the list,
    //using reflection
    protected void StoreResults (SQLiteDataReader reader)
    {
        if (fProperties == null)
            throw new Exception ("Store type definition is missing");

        while (reader.Read ())
        {                
            object newStoreItem = fStoreAssembly.CreateInstance (typeof(T).FullName);                
            foreach (PropertyInfo pi in fProperties)
            {
                string lcName = pi.Name.ToLower ();

                if (HasColumn(reader, lcName))
                {
                    if (!reader.IsDBNull(reader.GetOrdinal(lcName)))
                        pi.SetValue(newStoreItem, reader[lcName], null);                    
                }
            }

            list.Add (newStoreItem);
        }
    }

    public bool HasColumn (SQLiteDataReader reader, string columnName)
    {
        foreach (DataRow row in reader.GetSchemaTable().Rows)
        {
            if (row ["ColumnName"].ToString () == columnName)
                return true;
        }
        return false;
    }
}

And here how you would create Teacher and Student

public class TeacherInfo
{
    //Properties for store info from database
}

public class Teacher : BaseClass<TeacherInfo>
{
     public Teacher ()
         : BaseClass()
     {
         query = "whatever you want here"
     }             
}

public class StudentInfo
{
    //Properties for store info from database
}

public class Student : BaseClass<StudentInfo>
{
     public Student ()
         : BaseClass()
     {
         query = "whatever you want here";
     }

}

As the Read routine is public, you can call Read from any instance of Teacher or Student. You can even create them and store as BaseClass and use it directly if you don't need to know if it is a student or a teacher (for common routines, etc)

This is not an extensive example, but just a point in the direction you could use to turn your code more generic.

2
  • Thanks a lot! This is all new to me :D, so I have to work on it for now.
    – Mostafa
    Aug 21, 2016 at 15:32
  • @Mostafa, hope it helps. I suggest you to study generics, interfaces and reflection :)
    – Jauch
    Aug 21, 2016 at 15:34
0

You can follow the semantics of using interfaces to return the values and then cast the return type to an appropriate one, or use a base class (interfaces would be better, as you can still extend other classes as base classes while implementing the interface). The entity interface can be created as following,

public interface SchoolEntity { 
    // Provide the similar properties as members of this interface.
}

Then you can implement this interface in your Teacher and Student.

public class Student : SchoolEntity { }
public class Teacher : SchoolEntity { }

Finally, the parameter can be made a bit more clearer by using enumerations. They would be more clearer while reading, rather than having the same parameter types. Note that function overloading doesn't consider return type as a signature difference.

enum Entity { Teacher, Student }

And then you can check which data to return.

public SchoolEntity dbSelect(Entity type)
{
    switch(type) {
         case Teacher:
             var query = "SELECT * FROM Teacher";
             return dbConnect(query, true);
         // Rest of the cases.
    }
}

Note that, your SQL statement is open to SQL Injection and anyone can either drop the tables, or perform actions that can be passed to the engine.

Working in a list

Working with the list won't be a good idea. Afterall, what list would you return? Would that be, public List<Teacher> dbSelect or public List<Student> dbSelect? The answer and solution to this is to have a same type backing up these both types.

dbSelect function

Note that you are still returning only Teacher type, then why you are having a Student at all? You should definitely cast it back. As a matter of fact, if I had to develop this. I would have to the dbSelect function to take the Entity as a parameter to keep all of the database requests and processing in a single function.

public List<Teacher> dbConnect(Entity type)
{
    SQLiteConnection conn = null;
    SQLiteCommand command = null;
    SQLiteDataReader reader = null;
    Teacher result = null; // Can be set to null.
        //    try
        {
            conn = new SQLiteConnection(db.db);
            conn.Open();
            string query;

            // This way, leave the function to build the query.
            if(type == Entity.Teacher) {
                query = "SELECT * FROM Teacher";
            } else {
                query = "SELECT * FROM Student";
            }
            command = new SQLiteCommand(query, conn);
            reader = command.ExecuteReader();
        }
        //   catch (Exception ex) { }

        while (reader.Read())
        {
            if(type == Entity.Teacher) {
                Teacher temp = new Teacher(
                    reader[0].ToString(),    
                    reader[1].ToString(),                              
                    reader[2].ToString(),                              
                    reader[3].ToString(),                              
                    reader[4].ToString(), 
                    reader[5].ToString(),                              
                    reader[6].ToString(),                              
                    reader[7].ToString()                               
                );
                result.Items.Add(temp);
            } else {
                // Add the student.
            }
        }
    conn.Close();
    return result;
}

Now in this code, you are aware result is of type Teacher. There was no list there and this made your code a bit confusing. Take my advice: Re-write the code.

Please also go through the following useful links:

Explicit Interface Implementation
https://en.wikipedia.org/wiki/SQL_injection
Signatures and overloading

3
  • Thanks a lot! But dbConnect type for Teacher is List<Teacher> and for Student is List<Student>. As your first solution, I can't understand how dbSelect could return both List<Teacher> and List<Student>. If you could explain a little more, I appreciate it. Note: Thanks for letting me know about SQL Injection.
    – Mostafa
    Aug 21, 2016 at 17:43
  • @Mostafa, it will not. It will return List<SchoolEntity>, and you can cast it to either Teacher or Student later. That is the usage of having to implement interfaces or base classes. Aug 21, 2016 at 21:23
  • As I know about Interfaces, I have to declare members properties' in SchoolEntity (As you said), but properties of Teacher are different from Student, For example one have password but the other has not. So how can I use it in that matter?
    – Mostafa
    Aug 22, 2016 at 9:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.