How to Generate C# Business Object Class from a CSV File
To complete data binding in a model-view-controller (MVC) or model-view-view model (MVVM) application, you must define a C# class representing your business object. When connecting to an outside data source, such as a CRM, OData, JSON, or CSV file, your business object class will need to map perfectly to the data source. This is where ComponentOne DataConnectors can help with its scaffolding feature.
Scaffolding is a small, ease-of-use feature that generates relevant model classes based on the source entities while also creating the DbContext class. In this blog, we will show a quick walk-through for getting started with scaffolding using a common CSV file data source.
Ready to Get Started? Download ComponentOne Today!
C# Scaffolding Walk-Through
For example, let’s use this sample data.csv file (or you can use any you have lying around).
Set-up the Project
Open up or create any .NET application. For example, create a Console Application targeting .NET 6.0.
To take advantage of this feature, you’ll need to reference any of the ComponentOne DataConnectors. If you’d like to add one to test this feature, add the C1.EntityFrameworkCore.Csv package from nuget.
Also, you must add the Microsoft.EntityFrameworkCore.Tools package version 3.1.0. Please note that you must add version 3.1.0 of this package.
Generate the C# Data Classes
Next, we will generate the C# model class for our data.csv file.
Open up the Package Manager Console (under View > Other Windows).
Type the following command:
Scaffold-DbContext "uri='C:\...\data.csv'" C1.EntityFrameworkCore.CSV
Replace the uri with the full path to your CSV file. If you’re using a different data connector, make sure to change the reference.
When the command runs and builds, it will generate a data C# class that matches your CSV file, such as the following:
public partial class Data
{
public DateTime? Date { get; set; }
public float? Open { get; set; }
public float? High { get; set; }
public float? Low { get; set; }
public float? Close { get; set; }
public float? AdjClose { get; set; }
public int? Volume { get; set; }
}
It also generates a MainContext.cs (DbContext). This class can be used to represent an instance of your session to the data source. You may not need this file, but if you want to learn more, check out Working with DbContext.
Conclusion
The scaffolding feature of ComponentOne DataConnectors is simply a nice, quality-of-life feature, which is nice to have in your toolbox. Without it, you have to handwrite your business object classes which can become time-consuming the more you have to do it.
Download ComponentOne DataConnectors, part of Data Services Edition, WinForms Data Services Edition, and Studio Enterprise.
Ready to Get Started? Download ComponentOne Today!