dimanche 24 novembre 2019

Getting files in a directory and passing it to a Generic Class C#

I want to read all files inside a folder and pass it to a generic method to create a table.This is how my BaseRepository looks like:

 public class BaseRepository<T> where T : class, new()
    {
        public DbTableAttribute getTableAttributes()
        {
            var dnAttribute = typeof(T).GetCustomAttribute(
                typeof(DbTableAttribute), true) as DbTableAttribute;

            return dnAttribute;
        }


        public void createTable(T entity)
        {
            DbTableAttribute tableAttribute = getTableAttributes();
            if (tableAttribute == null)
            {
                Debug.WriteLine($"{typeof(T).Name} doesnot have a table attribute.");
                return;
            }
            if (string.IsNullOrWhiteSpace(tableAttribute.table_name))
            {
                Debug.WriteLine($"{typeof(T).Name} doesnot have a table_name attribute.");
                return;
            }
            if (tableAttribute.is_db_table == false)
            {
                Debug.WriteLine($"{typeof(T).Name} is not a database table.");
                return;
            }
            string tableName = tableAttribute.table_name;

            string baseQuery = $@"CREATE TABLE IF NOT EXISTS [{tableName}](";
            string endQuery = ")";

            IList<PropertyInfo> propertyInfos = getPropertyInfoList(entity);

            foreach (PropertyInfo i in propertyInfos)
            {
                var ca = i.GetCustomAttribute(typeof(DbColumnAttribute)) as DbColumnAttribute;

                if (ca != null)
                {
                    baseQuery += $"{i.Name} ";

                    if (!string.IsNullOrWhiteSpace(ca.column_type))
                    {
                        baseQuery += $"{ca.column_type}";
                    }

                    if (!ca.is_nullable)
                    {
                        baseQuery += "NOT ";
                    }
                    baseQuery += "NULL ";

                    if (ca.is_primary)
                    {
                        baseQuery += "PRIMARY KEY ";
                    }
                    if (ca.is_identity)
                    {
                        baseQuery += "AUTOINCREMENT";
                    }
                }
            }
            baseQuery += endQuery;
            execute(baseQuery);
        }
    }

Now I want to read all files inside a directory and pass it to this generic repository to create table.

var allClasses = Assembly.GetExecutingAssembly().GetTypes().Where(a => a.IsClass && a.Namespace != null && a.Namespace.Contains(nameSpace)).ToList();

 foreach (var type in allClasses)
 {
  new BaseRepository<type>().createTable();
 }

Error is shown in this line new BaseRepository().createTable(); stating

type is a variable but is used as a type.





Aucun commentaire:

Enregistrer un commentaire