Data Row To TEntity Mapping

Data Row and Entity Mapping Summary

DataRow to Entity

   public static TEntity DataRowToTEntity<TEntity>(IDataReader reader) where TEntity : new()
        {
            var props = typeof(TEntity).GetProperties();
            var entity = new TEntity();
            if (reader.Read())
            {
                for (var i = 0; i < reader.FieldCount; i++)
                {
                    foreach (var p in props)
                    {
                        if (p.Name.ToLower() == reader.GetName(i).ToLower())
                            p.SetValue(entity, reader[i], null);
                    }
                }
            }

            if (!reader.IsClosed)
            {
                reader.Close();
                reader.Dispose();
            }
            return entity;
        }


Get Entity List

 public static IEnumerable<TEntity> DataRowToLstEntity<TEntity>(IDataReader reader) where TEntity : new()
        {
            var lstEntity = new List<TEntity>();
            var props = typeof(TEntity).GetProperties();

            while (reader.Read())
            {
                var entity = new TEntity();

                for (var i = 0; i < reader.FieldCount; i++)
                {
                    foreach (var p in props)
                    {
                        if (p.Name.ToLower() == reader.GetName(i).ToLower())
                            p.SetValue(entity, reader[i], null);
                    }
                }

                lstEntity.Add(entity);
            }
            if (!reader.IsClosed)
            {
                reader.Close();
                reader.Dispose();
            }

            return lstEntity;
        }


你可能感兴趣的:(mapping)