My Entity Framework Cheat Sheet
This is a list of tools I use to get generated code and get work done quickly with Entity Framework.
Generate SQL/Database from a DbContext
Tip: If you are doing this a second time to rebuild your database (after requirements changes), you can...
- ... unload your Web or Api, Services, and Tests projects and just have your DbModels and DbContext projects open. That way you can rebuild the solution easily targetting just your Entity Framework related code. (Assuming you may have code referencing your DbModels which are changing).
- ... or if you are rebuilding only a subset of new tables, run a "Reset" migration first using this trick to omit the tables you are working on. Then remove the Ignore methods and run a second migration for those tables in question.
- For the entities, create a models directory and create classes in it.
- If your primary key does not follow convention name, use the [Key] attribute.
- Create navigation properties for many to one relationships; create a property for the ID and the object.
- If your nav prop ID does not follow convention, use the [ForeignKey] attribute on the object.
- Other attributes to use: Required, MaxLength, Index, InverseProperty, Column (if you want your db column to have a different name), [Table("TableName", Schema = "SchemaName")]
- Don't forget to make some fields nullable if necessary.
- VIEW > Other > Package Manager Console.
- Make sure the console is showing the correct project. You also may need to set that project as the startup project in VS so it can find the correct config file with the DB connection string.
- If you are trying to recreate your database, make sure to drop the DB or change the connection string. Also remove the Migrations folder.
- Make sure you have a DbContext file with:
- A good database connection string.
- Sub-classing DbContext
- public DbSet<Entity> Entities {get;set;}
- If you are using .NET Core, you will need a IDesignTimeDbContextFactory or a default constructor.
- Type: Enable-Migrations. Skip this for .NET Core
- Add-Migration MigrationName
- Update-Database -Script or for .NET Core: Script-Migration. Save off the SQL if you want it.
- Update-Database. Now your database tables are created.
Generate Classes for Entity Framework Code-First from an Existing Database
For EF Core, the process has changed. See the Scaffold-DbContext command.
For EF 6, the below process works well.
- Prerequisite: An existing database
- Do one time: Download Entity Framework 6 Tools for Visual Studio 2012 & 2013.
- Right click a project
- Add new item...
- Search for ADO, select ADO.NET Entity DataModel.
- Name it.
- Select Code First from database.
- Select / Create Database connection.
- Select tables you want to include.
- Finish
- Now you have models and a DbContext to work with.
Comments
Post a Comment