There is a function:

public IEnumerable<TEntity> GetAll() { List<TEntity> result = new List<TEntity>(); using (IDbCommand command = Connection.CreateCommand()) { command.CommandText = QueriesBuilder.GetAllQuery; Connection.Open(); using (IDataReader reader = command.ExecuteReader()) { while (reader.Read()) { var entity = Activator.CreateInstance(RepositoryInfo.TypeOfEntity); int i = 0; foreach (var columnName in RepositoryInfo.ColumnsInDbNames) { object value = reader.GetValue(i++); PropertyInfo propertyInfo; RepositoryInfo.PropertiesInfo.TryGetValue(columnName, out propertyInfo); //Тут нужно засунуть value в нужное свойство entity } result.Add((TEntity)entity); } } Connection.Close(); } return result; } 

It is necessary to fill the result sheet with the data obtained as a result of the query. If the TEntity object looks like this:

 [Table("Users")] public class User { [Key] public int Id { get; set; } [Required] public string Name { get; set; } public int Age { get; set; } } 

That Sql database query will look like this:

 SELECT [Id], [Name], [Age] FROM [Users]; 

The tables in the database always match the TEntity

In the class in which the function code is located, there is a List<string> ColumnsInDbNames , which stores the column names strictly in the sequence in which they are listed in the SELECT query.

The class also has a Dictionary<string, PropertyInfo> PropertiesInfo dictionary, which stores information about the properties of an object obtained using Type.GetProperties() . The key of the dictionary is the name of the column in the database to which the property of the object corresponds.

How can I assign the values ​​obtained from IDataReader to the necessary properties of an object?

  • What is the difficulty with you? Find a class property by column name, or find a column by property name? Or do you have difficulty with data type conversion? - nick_n_a
  • I do not understand the question. Get data, create objects with pens or use simple Dapper type ORMs tritac.com/blog/dappernet-by-example - tym32167
  • Implement a column traversal cycle — and if there are difficulties — ask. - nick_n_a
  • one
    @mirypoko handles - this is without ORM. If you need to create an instance of the type that is specified in the generic parameter from a row with columns, then use reflection (though the speed of work will be small) - tym32167
  • one
    For you propertyInfo.SetValue(entity , reader[i-1],null) - nick_n_a

0