IT:AD:EF:HowTo:Create a Model from a Database
Errata
- Late change: whereever you see 'AddModel' below, replace with 'DataModel' (it's a model of the data, not the app…)
Process
Create or use an existing app with the following specs:
- Ensure the App is .NET40+
- As per DDD design, ensure the app has the following assemblies:
Application,Domain,Domain.Entities, andInfrastructure.Data:- Create an
MyApp.Domain.EntitiesClass Assembly- Add to it a
ReferencetoSystem.Runtime.Serialization - Add to it a
Referenceto theMyApp.Domainassembly.
- Create an
MyApp.Infrastructure.DataClass Assembly- Add to it a
Referenceto theMyApp.Domainassembly. - Add to it a
Referenceto theMyApp.Domain.Entitiesassembly.
Create an EF Context
In order to create an EF Context In the App.Infrastructure.Data assembly,
- Use the Solution Explorer to Add/New Item/ADO.NET Entity Data Model
Overtime I've come to believing that the most apt name is AppModel.edmx – or AppDataModel.edmx.
Most apps will have only one primary model, and Model1 just doesn't cut it...

</WRAP>
Specify that we'll be looking at an existing SqlServer data source (eg: XACT-WS2K8-02)
so on the Choose Model Contents Page, select Generate from Database:

On Choose Data Connections :
* Select Db Connection...
* Give Connection Setting a Name of 'SampleEntities'

If it's the first time, you'll likely have to create a new Connection:


Upon returning to the main flow,
* ***IMPORTANT*** Set the App.Config's ConnectionString Name:

On the next screen -- Choose YOur Database Objects:
* Choose Tables /Views
* ***IMPORTANT*** Change the Model Namespace to App.Domain:

Inspect the results in the AppModel.edmx design surface:

But also inspect the code results:
* MyApp.Context.tt: for the Context
* MyApp.tt: for the Entities
* Under it you'll see the automatically generated classes defining the entities
## Additional Step if Using 2010 with EF5 ##
If using VS2012, you're good to go, as you already have EF5 and the DbContext template.
If using VS2010, you have get a beter Context.
* Right click on *.edmx designer and select Add Code Generation Item…
* Select Online Templates
* Search for DbContext in order to get EF 5.x DbContext Generator for C#
* Name it AppModel.tt`
## Next ##
In most scenarios you'll need to then move the creation of entities to their own assembly:
- /home/skysigal/public_html/data/pages/it/ad/ef/howto/create_a_model_from_a_database.txt
- Last modified: 2023/11/04 01:42
- by 127.0.0.1