Entity Framework 6 Tutorial: Learn Entity Framework 6 from Scratch

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
if you need to access a database in your application which most often you do you'll need a persistent framework with the persistence framework you'll be able to load your objects from or save them to a database now you can write this persistence framework yourself using plain a development classes like sequel connection sequel command and sequel data reader or you can use an existing persistence framework but writing a persistence framework from scratch is very costly you'll have to write a lot of stored procedures read the data using a detachment objects and manually map your data with tables and records to the domain objects in your application and this is where and the framework shines and the framework is essentially a persistence framework that frees you from all this dirty work you no longer have to write through procedures well in most cases or manage database connections or manually map the database tables and records to your domain objects entity framework takes care of all of these for you and that's what I'm going to teach you in this course in this section I'm going to introduce you to various course flows to build a model using editing framework and then I'm going to show you a demo of data base pairs and code for so you get an idea of the process just to let you know this section is purely an introduction to these workflows over the next few sections I will cover each workflow in detail so let's get started in this section I'm going to show you any defame work in action so you can quickly get an idea of what it is like to build a data access layer using any framework as part of this section I'm going to introduce you to various workflows when using entity framework that is database first code first and model first by the end of this section you will have a high-level understanding of entity frameworks and then from next section onwards we'll be covering the details so let's get started so there are three workflows to build a domain model using any framework database first code first and model first we database first of course we start through the database so we design our tables using visual designers and then have entity framework generate the domain classes based on the database this is the traditional approach that a lot of developers have been doing for years with code first of course we start with the code so we simply create our domain classes and then have entity framework generate the database for us this approach was introduced in more recent years and is still new to many developers and finally we have the model first approach with this approach we use a visual designer in visual studio to model our classes and their associations some kind of UML diagram then based on this diagram and the framework will generate the domain classes and the database for us I personally am NOT a fan of this approach and I'm not going to explore it in this course mainly because the visual designer for modeling classes is very poor and to be honest I have hardly seen anyone building software that way so our two main choices here are database first and Costra now over the next two lectures I will show you each of these workflows in action and then I will give you some guidelines about their strengths and weaknesses of each approach hi guys maash here thank you for watching my video I just wanted to let you know that this video you've been watching it's part of my complete entity framework course on udemy in this course over almost 7 hours you will learn how to use any framework to build a data access layer for your applications I'm going to teach you how to build a domain model using both the database first and the code first workflow you're going to learn about code first migrations to upgrade or downgrade your database you're going to learn how to override codes for conventions using data annotations and fluent API you're going to learn how to query data using link both using query syntax and extension methods I'm also going to talk about eager loading lazy loading and explicit loading you're going to learn how to add update and remove objects and along the way I'll also talk about some of the best practices when using anything works as well as additional tools that help you profile and troubleshoot your applications if you're interested you can get this course with a discount using the link in the video description all the best and have a great day okay in this lecture I'm going to show you database first work flow in action sometimes start with creating a simple table and then I will have entity framework generate a domain class based on that table so let's get started so here in sequel server management studio I've got a database called database first demo I'm going to create a new table I'm going to use this table for storing posts in a block okay I'm back on the table is ready now here's the tricky part of database first approach we have this database here locally but in order to bring a different database like a test database or a production database to this version we need a mechanism there are tools out there that can compare to databases and bring them to the same version but in my experience they are not always reliable and can sometimes cause issues due to dependency between tables and records and more reliable flexible but unfortunately more manual approach is to create a change script every time we make a change to our database then we can store these change scripts somewhere in the repository and run them on any database to bring them to the current version so in this demo I'm going to go with that approach so I'm going to create a change script here and or these and here's a sequence number and a description okay and finally I'm going to save this table okay so the table is ready in my database let's refresh beautiful now I'm going to go to visual studio create a new project and import this database and into tables into my projects okay so start with a new project I'm going to speak to a console application for now because we don't want to get distracted by the complexity of web applications or WPF applications so let's just keep it simple and focus on entity framework database first demo with a new project the first step is to install energy framework and to do that we use package manager console so tools NuGet package manager manager comfo so we run install package entity framework beautiful so here I got added Fame work version 6.1.3 now we go to solution Explorer right-click the project add new item a deal dot map edit a data model so this is going to be our conceptual model that represents the mapping between the database tables and our domain classes so I'm going to give it a name like block model and in this video I'm going to use energy framework designer from database because I already have a database next and here we need to specify a connection to our database so Microsoft sequel server continue okay here's my database test the connection beautiful ok next so at this point entity framework looks at our database and discovers the tables views stirred procedures and functions we have there so currently we only have tables and here's my table so I'm going to take all of this and leave the rest as is finish you get the security warning about running this template can potentially harm your computer don't worry about it so just click do not show this message again because Visual Studio is trying to run a template to generate some code I'll show you that in a second okay here's our entity data model which is stored in a file with the EDM X extension and here you see a class called post which is exactly like the table I created earlier let's go to solution Explorer okay let's expand block model EDM X what you see here is all designer generated code there are two parts that are important here one is the first one block model but context at T T so T T stands for T for template it's a way to generate code based on a template if the expand is we see the actual generated code so here's a Fisher PLAs that entity framework generated for me and this class derives from dbcontext DB context is a class that's an abstraction over the database so it provides a simple API to load the data from or save it to the database now I scroll down a little bit look we have a property of type DB set called posts a DB set represents a table in the database so because in our database we have a table called posts here we have a DB set of type post called posts now this post class you see here is a game generated code so back to solution Explorer the the context template so here's the template and the code that you just saw this DB context was generated based on this template now let's take a look at the other template plug model template so here's the template code and if we expand this we see the post class look it has four properties based on the columns are currently having the database so the key thing here is we started with a database we created our table and then we import that into our entity data model every time I want to make a change in my model I start with the database and then I come back to my admx file or entity data model and refresh it and at this point entity framework will update my domain classes as you see here so here's the database first workflow okay now let me show you how we can use a DB context to work with the database and this applies to both database first and code first so I'm going to close all the windows here okay then I go to program here I'm going to create an instance of our dbcontext class which is called database first model entities now I'm going to create a new post and initialize it here now in a real world application most often will use an identity column so we don't have to specify an ID here but for now it doesn't matter because I just want to show you the boy flow and finally I'm going to add this post to our DB set and save the changes so context just post the ad so we add it to the DB set and at this point changes our own in the memory nothing is committed to the database yet so context object changes that's it now let's run the application done so as easy as that note that ID have to write a stored procedure I did not have to work with a do dotnet classes like sequel connection and sequel command and the framework took care of all of this for me now let's verify that it worked so I'm going to go to management studio and let's take a look at our table there you go we got its record in the database now reading data from database is as easy as what you saw and that's what I'm going to cover later in this course so this was database first workflow in action in the next lecture I'm going to show you code first and then I will do a comparison between the two okay in this lecture I'm going to show you the code first workflow in action so here in Visual Studio I'm going to create a new console application and call it code first demo okay now similar to last lecture we need to install entity framework so tools NuGet package manager and package manager console install package entity framework beautiful okay now back to the program now with code first of course we start with the code so I'm not going to go to management studio and create a new database instead I'm going to create a new class called post so this post class looks exactly like the one that any framework generated for me as part of database / support flow but in this lecture I created it by hand now in companion for this class I also need a DB context remember TB context it's an abstraction over the database that we use to load or save data basically all we have to do here is to create a class that derives from dbcontext and expose one or more DB set in this case DB set of post next we need to specify the connection string to the database so we go to app config and here I create the connection strings element and add a new connection string I'm going to call this the same name as my dbcontext so blog DB context and the actual connection of string is in this case I'm using sequel Express you might be using a different engine so you create a connection string that works for you so initial catalog is the database name and integrated security means I'm using Windows authentication now one more element we need to add to this connection string and that is provider name which should be system that data the particular client this is required to work with code first okay next I'm going to go to package manager console we need to enable first migration so this is a command that we run only once for the lifetime of a project so enable migrations the code first migrations enabled for project code first demo beautiful now out of these few steps I have done so far installing edited framework adding the connection string and enabling migrations are steps that we do only once that's it every time we want to make it change in our model we start with the code so in this case for example we create a new class like post or modify an existing class the possibilities are endless now every time we make a change to our model we need to create a migration so we go to package manager console and use the command add migration and here we need to specify a name that represents the kind of change we have made in this example I created the post class let's see what happened so I go to solution Explorer look we've got a new folder called migrations and inside this folder we've got two files the first one is my migration note that it has a date/time stamp and a description and this is very similar to the migration script that we created manually last time remember I had to create a change script this is exactly the same process but in a more automated fashion let's see what's inside this file so interestingly we don't have any sequel code here it is playing c-sharp code this class create post derive from DV migration and it has two methods up and down so the first one is used to upgrade database and the second one is used to downgrade database so with code first migrations we can take any database and take it to any version whether that version is higher or lower and this is very powerful if you're maintaining different versions of an application this is going to be your best friend now let's see what's happening inside the up method so there is a call to this method create table it tries to create a table called post with these columns so ID which is an integer it's not not able and its identity state published in a daytime and it's not malleable and we have two more columns title and body they both are string and finally here there is a call to primary key method which specifies that the ID column should be set as primary key so the interesting thing here is entity framework uses convention over configuration so when it looks at our model in this case our post class based on the name and type of our properties it can figure out how the database should look like for example it knows that ID is typically used or the primary key and often it's an identity column so it automatically added these expressions here so we created a code first migration the next step is to run it when you run it energy framework looks at the database it takes the current version which I will show you later and then figures out what migrations need to run on the database to bring it up to date then it gets these migration classes and converts them to sequel code and runs it on the database so to run the migration we go back to package manager console and run update database so in this example it realized that this is the only migration that needs to be run on the database and of course we ran it so let's see the result I'm going to go back to management studio refresh the databases and here we have code first demo so I did not have to come here and manually create this database I just focused on my code which is much more fun for us developers so let's expand this look we've got two tables here on the line migration history which is used internally by added framework to figure out what migrations have been run on this database and we also have this Post's table with these columns which looks exactly like the one we created in the database first demo so as you saw with the code first workflow we simply focus on our code and let Edit framework take care of generating or migrating the database for us every time we want to make a change to the database again we start with the code create a migration run it and the database will be updated so this is the process in the next lecture I'm going to give you a comparison of database first and code first so database verse or code first well in my opinion that comes back to you and your preferences anything you want to do is possible with both code first and database first there are a number of misconceptions I've heard in the community especially on the Stack Overflow for example some developers say database first gives you more control over the database but this is actually not true at all with code first you have full control over the database even if the kind of change you want to make but nothing to do with your code let's say you want to create a trigger or modify the query behind a view or maybe create or remove a stored procedure you can do all of these with code first and I will show you later in the course I've also heard some people say that code first is good for greenfield projects and if you have an existing database you should use database first again this is not right at all because you can reverse engineer your existing database to create a code first model and then use code first migrations for any subsequent changes afterwards I will show you all of these techniques later in the course so here's the question again database first or code first again to re-emphasize you can do anything with either of these workflows but in my opinion there are a few advantages to using code for us first you get full versioning of your database you can bring your database to any version with running only one command and this is extremely helpful if you are maintaining different versions of an application without clothes first you either have to manually take care of versioning or use a tool like red gates source control but that's pretty expensive with code first you get these for free another advantage is productivity it's much faster to write code then use the mouse and a table designer we are programmers we are not designers if you are used to visual designers and wizards and clicking and clicking I highly recommend you to change your approach and start to use your keyboard more if you want to be successful successful programmers use their keyboard they don't use the mouse often anyway code first helps you get things done more quickly of course there is a bit of learning curve at the beginning and you may run into a number of problems early on but trust me all this will disappear after a while and you're never going to switch back I have used code first in many projects and even in production I'm not being very happy with it the only thing is where you work you might have a legacy database deployment tool and for that reason you may not be able to use code first because there are certain steps you need to follow to update the database and everyone in the team has been doing it for a number of years and maybe they are too lazy to change their approach then you have to use database for it if that's the case you have no choice but if you have a chance to change the system and influence your team to adopt code first that's great go for it or at least give it a try don't just stick to the old ways of doing things because some people say that's a better way always try different approaches and see what works for you so in this course I'm going to teach you both database first and code first so you can see the differences try them yourself and pick one that works better for you so in the next section we'll be looking at details of database first workflow I hope you enjoyed this section and thank you for watching
Info
Channel: Programming with Mosh
Views: 413,504
Rating: 4.8417478 out of 5
Keywords: C#, ef, entity framework, asp.net, asp.net mvc, asp.net core, entity framework core, ef core, ef6, entity framework 6, database first, code first, database-first, code-first, udemy, mosh hamedani, .net, wpf, windows forms, wcf, code with mosh, programming with mosh
Id: ZX7_12fwQLU
Channel Id: undefined
Length: 27min 57sec (1677 seconds)
Published: Thu Apr 13 2017
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.