EF Core isn't just for new databases. In this video, learn how to reverse engineer an existing database for use with EF Core.
- Hi, I'm Cam Soper, a content developer working on .netdocs here at Microsoft. Welcome back to Entity Framework Core 101. In our previous video, I showed you how easy it is to use Entity Framework core to create and work with a new database. In this video, we're going to show you how to use Entity Framework Core to work with an existing database by reverse engineering it. Looking at Visual Studio, I have a brand new Console app that doesn't have any code that are added to it at all. I've already added the new get packages. Same as we do with a new database, Microsoft.EntityframeworkCore.SqlServer.Design and .Tools. I have an existing database, this database is already populated and was built by hand by a database administrator. To reverse engineer the database and create my Entity model code. I'm going to use the scaffold-Dbcontext Commandlet. I'm going to pass in the connection string. I'm going to pass in the name of the provider, So it knows what type of database to execute that connection string on. And then I'm going to optionally specify an output directory and a name for the database context. Now that the scaffold is run, we have a complete working Entity model. Looking at the products Entity, it should look pretty similar to the one we created in the last video. One difference you'll note however, is there is no data annotations describing the behavior of these properties. For example, which one might be required or might be a key. That's because these behaviors are contained in the on-model creating method of the database context. If we'd like to create an Entity model that looks more like, the one we created in the previous video, we can do that too. I'll start by deleting this Entity model and I'll run the scaffold-Dbcontext command again, but this time I'll add the data annotations flag. This time the products Entity has data attributes that describe the behavior of the properties such as the key and required. And the on-model creating method in the database context is much more sparse. Now that we've seen how Entity Framework Core can work with an existing database. In the next video, I'm going to show you how to use Entity Framework Core with asp.netcore to streamline your web development.
This course was created by Microsoft.NET. We are pleased to host this training in our library.