I’m trying to learn object relational mapping and made my own method that accepts an object and maps column names to its respective properties in the object.
I would like to do the same when inserting by just specifying the stored procedure and map the property names of the object to the respective column names. But I’m unsure how I can go about this or if its even possible? Does anyone know any good c# object relational mapping tutorials.
I’ve provided my reader below which populates a list.
I’m just doing this for fun so I don’t want to use any ORM frameworks.
public static List<T> loadFromReader(string sProcName)
{
List<T> EntityCollection = new List<T>();
Type type = typeof(T);
PropertyInfo[] properties = typeof(T).GetProperties();
using (Connection)
{
SqlCommand command = new SqlCommand(sProcName);
command.CommandType = CommandType.StoredProcedure;
if (SqlParamterList != null && SqlParamterList.Count > 0)
{
foreach (SqlParameter parameter in SqlParamterList)
command.Parameters.Add(parameter);
}
using (SqlDataReader reader = command.ExecuteReader())
{
int columnCount = reader.FieldCount;
string[] columnName = new string[columnCount];
for (int i = 0; i <= columnCount - 1; i++)
columnName[i] = reader.GetName(i);
while (reader.Read())
{
object obj = Activator.CreateInstance(type);
for (int i = 0; i <= columnName.Length - 1; i++)
{
foreach (PropertyInfo property in properties)
{
if (property.Name.Contains(columnName[i]))
{
object value = reader[i];
if (value == DBNull.Value)
value = null;
type.GetProperty(property.Name).SetValue(obj, value, null);
}
}
}
EntityCollection.Add((T)obj);
}
}
clearParameters();
return EntityCollection;
}
}
It is not quite clear what problem you are running into but here are a couple of pointers:
You can see a sample here of how to get info on the parameters of a stored procedure This requires you to have the stored procedure matching its parameters ready.
If you want, you could create a more flexible system by storing the data in XML format in the database. that way you would not have to map the entities to stored procedures and or tables.