lundi 21 juin 2021

how to pass a generic type parameter in method

I have a generic class and have some method. The methods work is Insert, update ,delete in database using reflection. But my problem is I cannot insert pass values in Insert Method

that's the main class when I called my insert method, I can not pass values

MyORM class

public class MyORM<T> where T:IData
{
    private SqlConnection _sqlConnection;

    public MyORM(SqlConnection sqlConnection)
    {
        _sqlConnection = sqlConnection;
    }

    public MyORM(string connectionString)
        : this(new SqlConnection(connectionString))
    {

    }

    public void Insert(T item)
    {
        var sql = new StringBuilder("insert into ");
        var type = item.GetType();
        var properties = type.GetProperties();

        sql.Append(type.Name);
        sql.Append("( ");

        foreach(var property in properties)
        {
            sql.Append(property.Name);
            sql.Append(",");
        }

        sql.Remove(sql.Length - 1, 1);

        sql.Append(" ) values (");

        foreach(var property in properties)
        {
            sql.Append("@");
            sql.Append(property.Name);
            sql.Append(",");
        }
        sql.Remove(sql.Length - 1, 1);
        sql.Append(");");

        var query = sql.ToString();

        var command = new SqlCommand(query,_sqlConnection);

        foreach(var property in properties)
        {
            command.Parameters.Add(property.GetValue(item));
        }


    }
} 

static void Main(string[] args)
{
     var orm = new MyORM<StudentInfo>(DbConnection.connectionString);
        orm.Insert();
}




Aucun commentaire:

Enregistrer un commentaire