ADO.NET Entity Framework (EF) is an object-relational mapping tool included with .NET. It is used to automate database access. To use it, you need a data model which defines classes (or entities). Entities contain properties that are mapped to fields inside tables in a relational database. If you already have a database you can let EF automatically generate the model for you. However, if you don’t already have the database you can define the model, and let EF generate the database schema for you. This is known as “Model-First” development. Let’s see how it works.
Create a project in Visual Studio using whatever .NET language you prefer; a class library will do. From the project menu, select Add New Item and the dialog shown below will open. From the list of templates, select ADO.NET Entity Data Model.
After clicking Add, the following window will open. For model-first development, select Empty Model. Then click Finish.
An empty data model will open. The model is really just an XML file with the .edmx file extension. The XML is what defines the mappings, but EF provides a graphical designer for generating the XML code. Right-click on the blank model, then select Add | Entity.
The following dialog will open. Give the entity a descriptive name (this will be the entity’s class name). Notice, the entity name should be singular. An entity set will be created that is pluralized. The entity set will become the table name in the database. You should also provide a key for the table as shown below. This key will become the primary key in the database table.
After clicking OK, you will see the entity in the designer. To create properties, right-click on the entity and select Add | Scalar Property.
Each property is given a name.
Each entity property also has various attributes that can be set in the Visual Studio Properties window. These include the data type, whether nulls are allowed, its default value etc. These properties will be used when generating the database schema.
A relational database has tables, which have relationships. To define those relationships in EF, add associations between the entities. To do this, right-click on one of the entities and select Add | Association.
An association is defined as shown below. Notice, a one-to-many relationship between owners and their pets is defined.
After defining the model, right-click on a blank part of the EF designer and select Generate Database from Model.
The SQL code for defining the database will be generated for you as shown below.
This database script simply has to be run on your SQL Server. You can use SQL Server Management Studio or run the script right from Visual Studio. This will even work for creating SQL Azure databases if you are using the cloud.