Is there a quick way to generate classes based on DB schema by a few clicks in Visual Studio?
This seems a common enough problem to worth having an automated solution.
Solution: Turned out Microsoft has something to offer already. Its DBContext generator in ADO.Net entity data model does exactly what I am looking for.
Pr-requisites:
- create your relational database first on a SQL server, and apply physical foreign keys (FK). With FKs, the generator would add child collections in their parent classes. Below is my sample db schema.
- have DBContext generator template activated in your VS. If not, find it by searching online templates.
Steps:
1. Create a new class library project, and add a new item: "Data" - "ADO.Net entity data model".
2. Follow through a few prompts, and connect to the above database and select all tables.
3. Under the model ".edmx" branch, expand your ".tt" file to see the auto-generated classes.
Interestingly, the class name is changed from "Parents" plural to "Parent" singular. But, didn't bother to change "Children" to Child. Obviously Microsoft didn't invest money here to use an English dictionary. Lol.
4. Here you go - the nice and neat auto-generated code. Null-able types stay as null-able.
Very cool. Happy coding by not coding too much!




