# Mapping Data to Models: an overview

Instead of using each row the moment it's read, copy it into a model object, so the program can keep and reuse the data after the reader is gone.

Journeyman · C# · T-SQL · Updated November 3, 2026

## After this lesson you can

- Explain why rows from a database are copied into model objects

## Key takeaways

- A reader only moves forward and closes with the connection, so copy each row into an object to keep the data.
- A model is a class with one property for each column you need, such as `Category` with `CategoryId`, `CategoryName` and `Description`.
- Copying a row's columns into a model's properties is called mapping.
- Once rows are in a `List<Category>`, the rest of the program works with C# objects, and only the mapping code knows about SQL.

In the examples so far, the program printed each row the moment it read it. Once the loop finished, the data was gone: the reader only moves forward, and it closes with the connection. To show the products again, sort them, or hand them to another part of the program, you'd have to query the database all over again.

A better approach: as you read each row, copy its values into an **object**, and keep the objects in a list. The list lives on after the connection closes, and you can use it as many times as you like.

## A model is a class shaped like a row

The class you copy a row into is called a **model**. It has one property for each column you need:

| A row of `Categories` | A `Category` object |
|---|---|
| `CategoryId` = 1 | `CategoryId` = 1 |
| `CategoryName` = 'Beverages' | `CategoryName` = "Beverages" |
| `Description` = 'Soft drinks, coffees…' | `Description` = "Soft drinks, coffees…" |

Copying each row's columns into an object's properties is called **mapping**: mapping the data to a model.

## Why it's worth it

- **Read once, use many times.** One query fills a `List<Category>` that the program can loop over, sort and search as often as it likes.
- **The rest of the program speaks C#.** Code that shows categories works with `category.CategoryName`, not with readers and column numbers.
- **The database stays in one place.** Only the code that does the mapping knows about SQL. Change the database, and the rest of the program doesn't notice.

The next lessons write the model, map rows to it, and then gather all the database code for a table into one class.

## Check yourself

1 question to try on the lesson page.

## So what

Models turn rows into ordinary C# objects. From the moment a row is mapped, the rest of your program never needs to know a database was involved.

## Key terms

- [Model](https://www.ask-codey.com/glossary/model-c-sharp)

## Cheat sheets

- [Mapping Data to Models](https://www.ask-codey.com/cheat-sheets/mapping-data-to-models-in-csharp-an-overview-cheat-sheet)

Source: https://www.ask-codey.com/lessons/mapping-data-to-models-in-csharp-an-overview
