Code presented provides a developer with a tool to generate classes from a database.
An alternate is to install the following Visual Studio extension which requires a developer to open SQL-Server Management Studio (SSMS), select a table, right click and select CREATE To Clipboard and repeat for each table.
While the code in this repository allow a developer to create classes for an entire database at the click of a button and places these classes in a folder, ready to use but recommend adding your namespace to each class.
Supports VB.NET
and C#
(written in C#)
Code presented here provide methods to create concrete classes
from SQL-Server database tables
written with Microsoft Visual Studio 2019, C#, .NET Core 5.
When use of conventional DataSet/DataTable to store data are too heavy, similarly Entity Framework is overkill creating simple classes can be a great solution.
When there are a handful of columns in a database table it's easy to hand code a class with properties to store data while a table with many columns may be cumbersome to write by hand.
Within this repository is a Windows Form project which creates concrete classes for a select database.
- In the form load event in the project
CreateClassesFromSqlServer
change the server name if not using SQL-Express edition of SQL-Server to your server name.
DataOperations.Server = ".\\SQLEXPRESS";
- Set the project
CreateClassesFromSqlServer
as the startup project - Build the project
CreateClassesFromSqlServer
- Start the project
- Select a database in the listbox
- Click Run/Create button
Once clicking the Run/Create button a folder is created under the application folder named Classes, the classes are create under Classes\DatabaseNamme
.
Example
Copy all or required classes to your project and add a namespace if so desired.
Originally written to answer a stackoverflow question to Declarate each
property with a specific property attribute using a select statement found in ClassQuery.txt
. Have changed to the code to exclude the property attribute using a
query in ClassQueryPlain.txt
No guarantees that the code fits all situations
The project DataLibraryTestProject
uses one of the classes generated with the addition of editing the class and adding a namespace.
- Visual Studio 2019 or higher
- NuGet package System.Data.SqlClient
In some cases the type for a property may not be known and in these cases will have UNKNOWN
prepended to the SQL-Server type. In these cases a conversion will be needed.
For example [hierarchyid] needs to be parses using SqlHierarchyId.Parse via a read-only property.
Base code from a Stackoverflow post to a response for a question.