ASP.Net Core: 03 - Entity Framework Core Basics

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
so in this video we're gonna go through the basics of entity framework and linking that in with the SQL database so the last video of John shows how to install SQL Server have to generally connect create things and you know inspect the database so now we're gonna look at entity framework which takes the the need to manually write you know SQL or database in journal scripting and all the relationships and fetching from database saving to database and it brings it all into a nice just plain old c-sharp class basically so we'll get going with anteye framework i'll show you how to get it done easily without anything first just to show you working then we'll integrate it in the standard way into this asp.net core website this is just a complete copy of the previous MVC basics website that's on my youtube github so i've got a name space tester which we just change to change - space entity framework basics so we're ready to go with this we just press f5 and make sure this still builds and runs and your shows hello world for a home page just to show we've got it you know a working website up and running so now we've now got the because of relating the namespace we need to just edit the view imports so a job we started with that view imports to be offered only the using statements anyway we're not using this file so I just delete that out try that once more and then there we have hello world so we know we're basically below asp.net core website running so let's get started so the first thing you need when you're doing ASP what entity framework call is from just quickly create a folder this is usually be in a separate solution or select a project but for this we all just be all in this one for the example making you follow the called data that's well put all the entity framework stuff make a new class and we'll call this application DB context and this DB context is a database context if we override DB context class control dot to show the suggestions and include the right namespace control RG cleans up older or news namespaces and I'll get rid of the dot data in the namespace because I don't do that in my namespace styling so now I have this application DB context of this role basically represents our database connection if you will in the application and I rarely find the need for more than one context so you can think of this as your database in your database in terms of visually trying to represent things you can think of this level as the actual database so the database representational model application as well call this so we have the DB contact by doing this there sees entity framework so this is where your entity framework comes and we can now consume this add things and save and this thing would automatically create our databases save stuff and you know do everything we need so inside here now we need the table so we're gonna just make a settings table and just add some random settings to it just to show you the so to do that we'll have public properties and we'd have public and it's called a DB set which is for a table basically you can read a boulder the jargon there or just think of it as it's like a table this will be another class so you know each class will represent a row in the table so we'll call this setting data model I tend to call the tables and just then give a prop to the range settings I'll need to make another class which I swear make class use to make a class now you have to just select the class anyway it's no different than add item color settings data model patrol RG get rid of all the crap remove the data our settings database table representational model this doesn't have to override anything this is literally just a plain old class for Popo class just a plain old class object but this will represent each column each property in here will represent a column in the database so now a database for settings would need an ID to keep track of the specific settings we could help then a settings name and a settings value saved for this example so we'll just do public string ID public string settings name or you in settings so you just say name public string value must have all strings so that would work and you could save that and that create three columns in the database so I guess we'll start with that and then I'll show you the the things you can add to this after so let's keep it as simple as possible to start with to get you going so we now have a settings data model or at least comment this the unique ID for this entry settings name the settings value and then here we have the settings for the application and like say this will be a table in the database so we have all that in there the one thing we'll also need is to well well we'll put a constructor in there so we can see being created we will override on configuring because I'm going to show you this first initially without dependency injection is directly creating this class and using it so for that will see the configuring and we'll also eventually use the model fluent API stuff so we'll get these three in there we'll click all these and we will then need to at least connect to the database once we've done that this thing should be usable so when you create an instance of this class it will obviously create this constructor with nothing in and then you should see it or fire configure in a model so let's just start with that let's just jump to anywhere it's just going to here where the class starts up and it needs to be in using because it's disposable a DB context has a life span and you should really with contacts this should be a short-lived as possible because while you have a context created you have an open connection to the database so you want to really create your context Dewey database stuff and close the context by a dispose or just doing a using statement so we'll wrap it in a context and we'll just literally making new one for now so we have a new context and that's all we want to do so we'll hit there we'll hit there and we just want to see all the looking at here is the general construction of what happens when you run a DB context and what events get hit so you can see we get to here to create in your application context then it'll spin up the constructor obviously and now it's in here so you'll see nothing's actually happened with these two calls yet because we're not trying to do anything so if we then go in here and let's presume we wanted to actually do something so we could say database and contacts database which is the underlying database and there's multiple ways of doing this but in this example I'm going to show you basically ensure it's created to make sure we have the database because when you're using this context like right now we haven't made a database so where is it going to be so when your application runs initially or even when it runs multiple times or at any point in the future somebody might delete the database you might have changed it there's things that happen so this insure created will basically just make sure the database is created and the database will then be created based off this context and entity framework will analyze your context and your public properties and figure out that okay this is the database this is a table that we're going to default call settings that table is going to have three string properties with these names and that's where it's going to do it's going to actually inspect your Seashore class and construct an SQL statement and try and make a database from that so obviously this will crash because we haven't told it where the database is but let's at least run it and see if we get the constructor so we hit that makes the constructor we try to ensure the database this will then fire off the requirements to configure the database so you can see it comes in here with options and there's no options there's nothing been added we don't do anything here right now and then at that point it tells us there's no database provider so it doesn't know how to do anything at that point so let's do that next step so in here we can see it's you can stop the context here when you make the application then once we try to do anything with the database so this could have been a general call you don't have to be database and sure this could be context start setting aside and we could have tried to add a setting but ultimately whatever initially then tries to do something with the database it will then fire off this configure and this will only run once inside the context to configure the database it simply doesn't run until it's required so in the configuring we're going to then do options builder which has been passed into it and we're gonna say use SQL Server that's what we want to use and then it's asking for a connection string so we'll just give it one so we want server equal the dot and you'll see from this SQL video we can just open up SQL management studio and the dot just simply refers to this machine same as localhost doors but I like to do dot because it's for one it's the short Eastern two there's no confusion so just a dot there you can see and trying to connect to basically this machine with my login and that connects so the connection will have it should be in here and I'll just delete this database so we have a database already in here but we have this connection is what we're looking at so that's the server we should be looking at and database will say equals entity framework semicolon I think that's right yeah we'll just use trusted connection which I mentioned before simply means use my logged in windows account to connect to the server which is fine in this instance and that's all you technically need I like to also add multiple active result sets which means by default some databases only allow you to be running one query at a time not embed in a query and then running another one while that's running but entity framework I'm pretty sure needs that so we have that anyway in there's no major harm in doing that so this is now the connection string so if we run again it should actually be able to create connect to our database and actually create it because my user my Windows user and add me on the database so it construct that we try to ensure the created goes into configured and now you see it's got past that configure so now it's gonna try and create the database so to create the database it then wants to know well what's the what's the public keys what are the relationships what's the general connections with your database so obviously right now we just have a settings data model which is just class there's no relations there's no public keys even though there should be one you know there's no defined things there's no set sizes or anything like that this is what the model creating doors and we'll do that later you can define things like you know relationships between tables and database specific stuff so it tries to do that before it creates a database once it does that it's going away now and analyzing your structure creating the SQL code and then you'll see it dump out the actual sqi run and we should see a database created so now it's got passed and if we tap back to this doesn't show us actually it should though we usually see output here of it actually you know doing if I'd only just double-check well I'll ignore the output I know why I'm about at this minute this is running in is Express not kestrel but if we at least go to databases you can see now we've got entity framework tables and we have a tables and we've got the columns that we specified it looks like it's actually been smart enough so I'm guessing it's e brainwork has detected the word ID and turned it naturally into an ID for us without just defining the ID so there's just that extra bit of intelligence built into entity framework the last time I did something from scratch with it so I'm guaranteed they baked that into detecting the name ID and and automatically turned into a key because we have not told it to do that so it sadly the key for us which is nice I'll kind of prove that so first let me change this to Kestrel so we get some output or in fact it is Kestrel so we should have got some output them with that log but never mind so let's just go back and delete that database a minute and let me just prove I don't need to burn I'm just interested now I'm pretty sure this the reason this has got an ID he's become an ID it's because it's called ID so let's put something else and let's run that and see if that still becomes an ID and I'm pretty sure it won't we should end up with a table with no IDs so the usual runs through we've now seen these hitting so we don't need to really breakpoint on them for now and there you go the entity type settings edge model is quite as a parameter which is good because we should in all tables have a key so you can see that basically you are forced to make a key but by default entity framework was going well as this field that's property in your model is called idea we're going to presume that so if that wasn't the case and even when it is I like to explicitly do a date your annotation and you just put key control dot to give you the using namespace you require and now this data annotation will tell this column to be the ID and by default it being named ID entity framework automatically I leave that key for us this time it won't so we're explicitly telling it which one is the ID but either way as I mentioned when we have a column I always tag it with key so it's explicitly obvious what's a key what isn't you know you want to see database structure so that's now been made so we refresh here should see the table again and you can see now something else is the key and you can see by default everything is before Carmack's well every string we have is var Carmack's and it can be not the key has defaulted to 450 in length so it's this is entity framework making these decisions for you at this point which is fine but we will configure these specific so I'll delete the database once more we know that now runs we hit there so I'm gonna name this back to ID but I'm gonna keep that I that key in there so visually tours it's obvious that is that the unique ID and then in here this name I think personally I feel it's a bad idea to have in a database end of our car which is for Strings set to max because that limit or something like 2 gig if not more so that means somebody could inject a a name of two gig worth of string and a value of to get that's four gig for one entry and kind of spam your database and instantly make your hard drive from that space within a you know a few seconds so I always like to apply you know max length so if I do max length attribute will say the max length of a name I would beat you know two five six a for the value maybe 2048 and these roughly multiples of two so the that's why I'm picking the what might seem like random values though at least multiples of tube that's how computers like to work anyway so maybe adds a bit of efficiency maybe not cook I tend to put limits on like that and then to get rid of that null option right when we made the database manually you can just set i think it's required as there well yeah so if we set them both to be quiet and we run this again you can now see we're basically starting to tell entity framework about even though it's just a class in c-sharp with some annotations on or effectively constructing the database in that wake we're applying our requirements to the underlying database but with data annotations so we could then move to you know a MySQL database or any other database and we wouldn't have to do anything at all other than reconfigure that use SQL server to say don't use MySQL instead so you can see now that those limits have been set for us so we've now got the data there it will have no entries in there so we said select all them settings we've got no results so that is what it is because we haven't done anything yet that's fine but now if we've got the database created because I haven't deleted it this time and we rerun you'll see you'll hit bar and it'll carry on because it's done some checks to see if the database exists and it has so it's simply carried on and that's why that's happening if we went to SQL Server management tools SQL Server profiler we should be able to see these commands coming in so connect to this machine I'll select the template of t-sql duration just that's a handy one for generally visualizing this and this on monitor all all requests to the database so if I then run this again and we should see I pull this off to this side not to that side that's the wrong one this to the side and then we can see into your database if I step over that now you can see this is then caught the request that entity frameworks made and it's done if exist select all from schema tables where basic table what basically it's looking for you know the table and if it finds it it's quite happy to you know it doesn't need to create the database so that's what it's done there so now let's actually do something with this so we've got the database we've ensured it is created and now let's say if there's nothing in settings let's add a setting so we'll say unless you tell you then effectively query the database so like we've done in here select all from settings and there's nothing this is similar to doing that you know want to get the settings but you can use C sharp and link to new context settings and this is now the database table settings and you can say any just like you wouldn't roll button are living but you can just say any a normal c-sharp link expression and you can say if there's not any so basically there's no entries in the settings database table and we want to add a set and so it's again as simple as saying context settings got add and now we make a new settings data model on normal c-sharp class and we'll say the name equals I put my name in well this is a setting so what's our background color and the value can be read now you might think that's it but what you don't do in SQL you shouldn't is say we're doing a lot of things like we're adding this multiple times or doing certain things every time you simply run this command you don't want this to go straight to the database and do a query or do a commit and they the next line does another commit you want to batch all of these into a single transaction or the small e set or a stored procedure and that's all kind of that's high level database stuff or other low-level database stuff that's you know you don't need to know now because of entity framework but in general it's more efficient in a server to combine multiple queries and commit them at one point in time as opposed hammering the database a thousand times for a thousand requests so just biding context to add now our in-memory context like as in that this object in code right now we could do settings for example number of settings you have contact settings got can't ortho or yeah enough to do pop count cause it's in your rule so could do count and get the number of settings and that's will be two and one but it won't be in the database at this point we could also do get that settings back there context off settings and I think you can just user maybe use indexing no so just a fuse link so just do that first so we'll do that we'll run this and you'll see for one the indeed won't get added to the database but it will in our c-sharp code appear that way so so things start any we don't have any so we're gonna add settings so we add a setting now we say how many settings have we got oh so in fact you don't now get the value before committing which you used to another secret work so the point of showing that was then gonna be to show you that it's in memory and in fact that is showing one oh so now it looks like they've changed it to a local so they've added this which is handy so there we go that's nice so what you have now before in entity framework when I was using it at the you know earlier days like six months ago say at the start settings dot count would always return the what's called the proxy so the in memory State the database because you have two states of this database you connect to it you do things you add stuff but like say this doesn't go straight to the database so at this point in time you have a state of the database locally which is in memory in entity framework but you also have the physical database which is when you you're simply query it without saying dot local as my presumption because I've never seen this this is a new feature but I'm pretty sure that's what it's going to do so now we can define we can check what we have in memory before we commit to the database and we can also compare it to what we don't have so what we can say is settings locally and settings database and we can do that so we nobody changes to first or default so then one could say first local first database let's run this again and then you'll see there and this is important to understand as well so when you query in your code you know exactly what's happening so we add the settings there well locally now hopefully is one which it is and the database is none the first local one should be this thing we just added which every loop it says and you can see entity frameworks also just made a new GUI to forest for an ID key by default which is good so this is now in memory ready and the first in the database is not so we now have the database context the settings table ready and we can always create with local and find out where we're up to but if we then finish running that code and we actually check our database you can see there's no results so the only thing you need to do to effectively save to the database when you're done which is kind of at the end of your you typically do it at the end of your context there's it's obviously based on your situation you know when you want to do it so for now I'll just rock it here and I'll just do Save Changes and that's well commit to the database so at this point we should see changes hitting this query here so then we can stop start the under clear yeah so when we hit that will then rerun these so let's run this again there are nothing on here yet then we can see the attempt to check the database existed which was there nothing's in it which was it actually query the database there select case select warm from settings and then cast wander a bit and basal Asia you check for settings not any hitting the database if not we add it and you can see nothing happens so if we stop start that is it this isn't hitting database right now if your local also won't hit the database but now this check for the database should hit the database and there you can see it's doing a selects count from settings so basically you should seen how many settings are in first local as local it gets that and then again the database it's gonna try and select so it selects top one the ID to name the value from settings he tries to load everything so I'll clear that off so you can see there's nothing in the database right now let's just triple check that there's nothing there now if we save the changes you'll see there now it has run a stored procedure that it makes basically and inserts into settings values 0 1 & 2 and then those values are all here so you've got the ID the background call the vet so that point you've saved changes we refresh here you think now it's in the database it's been added the local count is 1 the database counters 1 the local counts 1 and that were rather the local is there and the databases that's in the same instance so that's kind of how entity framework is working so you have your context that's like your connection to your database you can think of us that the representation of the whole database but you you spin up a context in a short frame to do just what you want your database queries then you close it off cleanly top keep them active and sure created make sure the database exists which again we'll talk a lot more about that in future videos about when you should do it migrations instead of just and she'll create things like that but for now we'll just drop that in and you can see that's the thing that checked every database exists and if he doesn't creates it and then doing these the linked queries these hit the database directly when you're doing dot any if you do dot local then it's the in-memory context so when you add to the settings or you remove from settings same thing the remove won't happen straight away nothing will happen to the database other than gets so when you're doing like you know get you trying to figure out if there's anything in the database that will hit immediately but when you're saying adding to the database deleting from the database transactional things they don't happen until you say save and that's at which point the data based commit happens and if you want to know what happens it's as simple as I opening an SQL management studio tools Server profiler which is what we've got open here and then just go in either file new trace or when you first start up and there's nothing open you get that window anyway so it pops up like this connect to the database where it is and then I always select t-sql duration is just a template with the right fields in and then you can sit and inspect this and even if you run it manually if you just refresh this select statement and then you go back to there you can see there's our select statement so this is like a a nice quick way of seeing statements come in so you can play around with this have a mess with the settings and and and get a feel for it but the most important thing to remember is one keep this as short as possible the context and then two is understanding when you're adding things if they really are in the database yet or not when you're removing the marthy and this new local thing which I've literally just learned live on this video because I've only done entity framework from scratch just now I did he obviously when it first came out and I've now made large applications really but I've never gone back to the very basics and and retested my logic if you will whereas before he didn't have locally just had doc count and this would always return the local instance there was no way to really check the local versus the database so this is a really cool feature so the local axe is the in memory stuff that you do in here and the the direct query on there is the live hit in the database to see States and then Save Changes saves the database context so this is how simple it is to use entity framework through basically DB context that's the key to it but that is not the normal I wouldn't say the normal will certainly do something just like this in code but the way you didn't agreat it into an asp.net core website and the way that templates will do is slightly different so we'll show you that now so we'll start with some code we'll cut this out the way or for now I'll just comment it a minute for now I'll cut it all the way I'll just chop it in notepad your suits out of the way so now we're back to other than creating this context we're back to the the standard default website we made this now we want to change the context because well you can't change the context you might want to leave it that way it all depends how you want to you know get your database but I would recommend now removing this from here because we want to configure it through dependency injection instead gonna cut the connection string because we'll use that but you can remove the on configuring we're going to do nothing with that now the constructor of this context instead of being blank and then effectively having to configure the connection string here which is what we were just doing we want to instead have these options already passed in as a constructor and that's kind of our this class telling the the thing that wants to insensate it that this is what we expect so have DB context options of tag application dbcontext called options pass them into the base DB context so that that constructor can also be given them and that's now the new constructor so constructor default constructor Expecting database options pasty in name options the database context options so us the constructor done now so now whenever we want to make an instance of this we'd have to pass in the options but you'll see in a minute we'll do that through dependency injection and this creating the model can stay there for a minute that's that's the first change next change is we will be adding the actual database injection here in configure services so in dotnet call a service collection this is part of the dependency injection so this is where you inject your dependency so that's how we added MVC that was a dependency we injected so in the same way we'll do services guard dbcontext from allowed application DB contact so now we're injecting this application this entity framework context so dependency you can think of this like the N inject that is like doing kernel top bind and when I was saying this is a context that we want to bind you would naturally add services to the collection just using like ID transient add scoped and we'll talk about dependency injection more in another video but that's what you ultimately do you add them in whatever situation you want to get them in singleton scoped or transient but for now we use the helper add DB context because ultimately that code if you just typing get hops or code add dbcontext you'll find this source and I'll try and remember to put the link in the video if you want to see what this does but basically this just adds it does services ultimately boils down to doing services to add scoped and ads this isn't a scoped fashion and the scope is whenever controllers are constructed so whenever this class gets created a new instance of this context gets created and this class gets created for every single call to an action in there so every single request you make to the webpage creates a new controller every single time which you might not expect but we can show you you know we will show you in a minute so this ad dbcontext does ad scoped which means the dependency injection of work and I'll show you how to pull it out a dependency injection in a minute and then the part we want to add here is the constructor which is expecting options so for that we'll do options and we will then do options dot use SQL Server just like we get using the exact same thing options just it should be use SQL Server we're just missing the namespace so yeah use escrow service we're back to where we were we could just dump this in here like this and there we go we're done if you will so this replaces the having to create a new instance of the application and instead we bind it in dependency injection and then we pass in the constructor arguments here this way so let's just leave it there for the minute so you don't we don't get any more steps confusing this specific setup so add application DB context to dependency injection that's that step what else do we need to do I think that's it so now we've done that instead of then creating an instance like we did here we could then put it here but let's now move it to somewhere in the application instead so let's just go into the controller so now here whenever their home page is hit we originally would have run context is new context and we'd have to dispose of it and clean it up and things so instead of doing that now we could say get the context this way well there's one other step it's like with n inject where we want to get the services a specific way you know you want to get there if you want to get the dependency injection container to be able to say well get me this service I want this service you might say right now where is that service in this there is no service or such so action but you want the service provider the thing that can give you the this service again so the trick is here in the configure setup we just add a service provider which again I think is a missing namespace yep alright service provider let's call it service I've got this service provider this will now funnily enough be naturally provided to this configure it will in itself be injected almost every well so by just simply ask him for it here will get this service provider and this you can think of as the ioc container in like Fassett a word application this is like the n inject kernel but this is obviously the the built-in dotnet call dependency injection provider so also need to do now is keep an instance of that and then we can say provide a doc get and get what we want so in a similar fashion to the facet a word application i was create a folder called IRC in there a lot of class and we'll just call this again to keep it simple IOC container but we will have or call this started class IOC and we can have an ear public static I service provider and then for now but again just for the demo we'll just do a get set IOC dot in fact now we will keep the class called IOC container and we will have this called provider and then we'll have another class here which is a shorthand ones like we did just IOC to do quick things so then we'd have in here probably application to the context taking DB context and that's just going to be a shorthand for ioc container dot provider top get service I think you're then passing a type so it will be side of think this is the way I'm doing it sure that's the way I just don't remember doing type of now you don't do type I'm sure you just do that but it's not showing I might be missing namespace again so that should be the way we do it are we just missing a namespace mmm no I say public static for one get rid of that era provider I service provider get service the non generic method cannot be used in this type augment do we have to do service provider okay so don't do the interface do service provider there we go is that gonna complain yep there we are so so much for idea you can do interface here but then we can save it to that so this would be a static class for ioc container so the dependency injection container making use of the built-in botnet core service provider the service provider for this application this we need to set so the mob yet well there should be a nice way we don't want to be able to anyone to override it but for now I'm not really bothered if it can be it might be able to make it read-only and set it once maybe we do read it well leave it as that for now I'm not really bothered just the point if somebody could change the provider but this is just an example so we just have a static class ioc container that's accessible everywhere in the application and then inside that a static provider and this is what we're trying to get to simply the provider and then we just make a class up here which is just a quicker shorthand in code throw a shorthand access plus to get di services with nice clean your code so just save you're having to say IOC container dot provided or get service blah blah blah you can now just do I Oh see the application give you contacts to get the same thing so that's all we're doing there and now all I need to do is save this provider so in here store instant store instance of the DI service provider so our application and accessing anywhere so we do is e container dot provider equals and if any of you've got a suggestion on the like a nice way to do this if you will you free to comment so a way where only this startup class can set the containers provider and we get rid of the setter that I can do it but I can't be bothered putting thought into right now so if you have any nice suggestions of how to make this a it's only accessible from here so nowhere else in the application can edit it and we can always guarantee this is then set then feel free to suggest that so now that'll be the scoped instance of the application dbcontext so all that's now boiled down to in here now when we're in this context and we would add on new application DB context we should be able to replace that with IOC that application DB context and this should give us the scoped version now because this is scoped meaning the dependency injection provider this provider is handling the lifecycle of this this provider will naturally create the instance for us and then dispose of it when the lifecycles done so that means we don't need to do the using because all's the using does if you don't know what are using does as it does save are a new application context you do your code that's inside the using statement so you do this code here and then at the end of the user Damon Tito's a doc dispose so that's kind of what a using statement does it wraps the thing that you've done there and simply calls contact dispose at the end of the using statements even if the code crashed inside but we don't need to do that because the provider this provider is doing it for us so we remove the the using statement the code would become this and that would be exact in code we need to add the link stamens control dot to get the pop up there and you can see now the codes exactly the same the only thing we've changed as where we get the contact from and we don't dispose it and all this does is e the application do the contact calls ioc container dot provides don't get service and the provider is basically the built in dotnet core dependency injection provider that we pulled in here so presuming that cast is right we'll get that then when the page loads we'll get here and then we should get an instance of the application context let me do one more thing to show you or to give you an idea of the scoped context but we'll do this in another video anyway let's just do public string in fact cambia public strings because ill man go to the database protected in fact it can't because in our DB contact public string ID it get set equals go with dot new gooood system there we go give it got new gooood doctor string so basically every time this plus is instructed we'll hit this ID and go new string and then every time we get here would be able to look at that so if we've run this application now we're human I've done nothing wrong this should build and run and do exactly the same thing so we get the service provider it's been injected it does service provider which is good so a lot of cast fine so now we've set the service provider let the application run this spins off opens the web it makes a request to index page when we get here so now we ask for the context which will basically go into the IOC and it should get the contacts now you can see we've got a context here and we've got an idea of six three you know big long number but got an idea six three so now the rest of this course should still work we should be able to do the thing we've already got a setting so it's not gonna do anything and that goes away and finishes serving our page so we get hello world we refresh get the context again and you'll now see we have in fact we got the same one six three D which we shouldn't have so we're not getting the right scope here let's go into the constructor run that again refresh yeah so we're actually getting this should be getting it this way which again I say we don't actually usually get it this way this is causing us to get the same instance of the context every time so that's not what we want in terms of accessing a context because then it's a single instance so this wouldn't be the normal way you'd get the context anyway so let's change this off because I'll do a video on dependency injection and scopes and everything anyway so you don't need to be worried about the scope being wrong there because we're gonna do it a different way anyway I was just showing you the way you typically access a something that's been injected into the dependency injector and this is how you can get it so this will still work but you've got the same context all the time here at the minute so now if we were to want to get this context would usually be in you know well it should almost always be in a controller that gets passed through instead of having to do I or see that application context you can do it in a constructor so if we would make that's constructor for this controller we could then request the application DB context in here by just literally adding it as part of the constructor arguments and then we could store it so we could have protected member and this is where we'll store the context so we'll do the context there this scoped scope the context or scope application context and then the constructor II shall be injected here and then we set the context here so this is the alternate way of doing it now as I mentioned the controller will be created every single time that you request a page so this then I'll just change to and context all the way through so just replace all them and then we run this code and we should see every time we request a page we'll get the application injected but it should also generate this which would be hitting us every single time or maybe yeah we should get eNOS every time so we get the instance we set it and in here we have context of o66 we do what we want that's one page loaded with refresh and we get the constructor maybe it's just my code of yeah and there we go we got different ID so this is now definitely scoped so every single time we hit a page we got a new constructor it injects the context for every context we get it's a different context hence the you know the changing ID so I've got a breakpoint on the get or not the setter so that's why we're not hitting this breakpoint let me just break this out too in fact yeah we should have I change this to Justin Jetta then we'll always get that running we should do so we can see easy we should get a breakpoint every time the applications being constructed so this time we hit and we're still not hitting a break man this is really annoying just want to hit a breakpoint why are we not hitting a breakpoint or that something because we're not requesting it as well so get will return set we'll just do well but we don't need to set it's only a getter yeah why are we not getting this hit this debugger should construct this every time this context spins up we should be hitting this instance here which is really strange because we're not getting the debugger hit in this instance so why is that because that's a getter that should get there so and while that's a getter which is fine but the get set equals should hit this line maybe I can just do it on a new line to always hit that so that should hit when the constructors run because it's setting a public property I think we've just been on the same line it was throwing it to there we go so the applications being instructed if we looked at the call stack where we are you can't see because it's been it's coming from entity framework so it's just come from nowhere you will constructs gets to there we get into the controller and then we've got obviously that new instance and then when we refresh the page it construction another one spins it all up in Jax the new one and then we run with the new context that's running every single time and this is the standard way you'd usually do your access to dbcontext you put it in the constructor of your controllers you'd save it as a property in the control because that will get disposed of so then this would get exposed off by the dependency injection not by the controller and then you've got access to it here so even though it looks like you've got a fairly long live context because she'd might presume the controller gets spun up once and and stays alive that's not the case this controller gets constructed for every single request that happens this effectively scopes this context to be a new instance of the context for every web request that hits your server which is the kind of lifespan we expect for that the context in the first place so all that's change there is you can get rid of that for now the constructor now expects these options passed in the service services the IDB context here does that so we passed the options in here so when we dependency injected it will pass in these options each time into there the constructor for us and that's where we get it then we have the controller itself we then make a constructor where we pass in through this is the thing that gets injected via the service provider us simply how it works so let's call the constructor injector that will be given to us because of the fact that we've added it here the services we've added it as a service so then when it tries to create a controller it will be injected in the constructor we store that there and then we've got access to it again so that's kind of how we're doing it here we can do one more thing now which is to move in fact I mentioned I would show you the context model creating here so one of the things we should see would enclose that profiler down we open up this fall again you can see here we have just a key of P settings indexes settings clustered so if we then wanted to do something different with the model you've got two ways of doing it you can do it in the actual model itself as in like the data model and do these tags and required max lines and things or you can do it in this model builder unless he called fluent API I think that's how you spell it fluent API and in the model bill do you do model or entity and then you get your specific DB contact your DB set out of this so this one here it's now it's referencing that table if you will and you could say things like has alternate key has index has key has many as one these are database relations so will say has index and we'll say aid after then you'll notice now it's inspecting a settings data model so a is a settings day tomorrow so we're gonna make name an indexed column and by doing that right now because we're not migrating databases which we'll talk about in another video I'll just delete the database so if I go how to delete the database close connections should delete it for us fine and then if I run this code again when it creates a database this time I can get rid of that breakpoint we should then have the name as an index in the database this time because we've done it through the fluent API which is like say the same thing is doing it through the actual plus itself here but we're doing it a different way so it's created the database refresh tables settings and now hopefully they can see it's added an indexed to the name column so now the name column is in next due to the on moral creating so this is configuring the database columns the same way that this is so certain ones you can do in both ways so that required you can do because I believe you can do housing next up is unique and and the unique is the same as that's required so you could get rid of this required have it as unique here and that's the same thing so it's a combination of the two now unfortunately some things aren't available in attribute form so like you can do index there's no indexed one so you can't tell this column to be indexed in data annotation style whereas you can do everything in fluent API there's nothing you can't do in fluent API to configure your database so I would usually suggest at this point to keep all of your logic in the on model creating but that means you have to win one DB context configure every single table and every single relationship in this not as obvious style like what's more obvious that you've got model builder entity settings data has index a name is unique for is it much easier to say required and if you could index which one looks easier to you know you can clearly come to a thing here and see what's what so even though this means splitting up your logic between data annotations and fluent API so like now you don't know this name is indexed because it's not set here it's it's not possible to do a few things directly and here like you can't do a one to many relationship mapping because how would you define it so what I would recommend is I'd still do as much in data annotation as you can so set them as required set the max length set the keys set anything you can in date your annotation style and then what's left that you can't do do in fluent API and probably make a note here in your settings data model or a note in each one of these as remarks as to you know this column is indexed bought something Lila so you've got you know some remark that makes it obvious that it's been done here so you can get rid it is unique now so that's my kind of recommendation of how I'd style and construct them you know put limits on databases so I think that's enough for covering the basics of the entity framework one more thing I will quickly do is to that's all fine know their comment there if what the instructor the injected context rattler region and we will just move the connection string into the app settings so into the built in settings thing of dotnet core that's one last thing we'll quickly do that's there that enclose that's done startup so we'll now move the string out so what cut this and instead we want to point it out settings so app settings again I mentioned these briefly in the MVC startup guide if you will the basics guide this is again built into dotnet core in a sense so you can figure it so in the program here we we did it ourselves we made a new web host build of an added just what we want but I mentioned there's a built-in web host dot create default builder which adds a bunch of default things and one of those default things is to add the app settings and the app settings dot develop if you wanted to do different configurations so that's part of that but we haven't added it because we remove the build and then added what we want so if you wanted to add it this way you do use I think what it says things use configuration I always forget this one it's not set up isn't now you do so it's use application something it's put its in a namespace so the way we could find out if you wanted to do it manually is web host create default builder we could look for the source code of create default builder it's in a namespace I'm sure it's more like use app configurations or something like that or use up configuration I can't remember the the extension but if you just look at the source coding github for this that we did in the last video anyway you'll find that it just does a setup option you know it does it does it use and then we specifically add app settings not jason and things like that into the configuration so what we're gonna do for now because I only did this version to show you how to do it without doing any of the basic you know the default stuff we're just gonna make use of the default binder which will automatically add that and a few other bits anyway so then we won't need that we only that was there both added' so changing that to create default builder will automatically now give us the way to access these settings so now in here yet we'll do I believe its connection connections rings or connections settings which one is it connection strings I think and then put a comma in there and that will make one called default which is just the standard thing new default connection and that will then be this string so we've moved the connection string into this app title instead and now in here we can do figuration dot get configuration string default connection and that should then pull it out of the app setting instead what's that complain about one another one of those yep now this is in so have a quick look out to curiosity configuration access 9 next edge yes that's fine so now by changing that and changing this we should still pull in the connection string so then of your way of making sure that's happening one you could just extract that into a variable and look at it and the other is now to spin it up this way so it must have connected because ensure created worked what you'll also notice is now because we're using the the configuration stuff with well not necessarily using that because we've changed it to where are we not this program because it done this create default binder on top of adding their application settings it's also added the locker so we're now getting the built in dotnet core logger which is now outputting the log information so you can see that it's it's outputting the actual SQL statement so you don't necessarily need to open the the SQL profiler to see the statement because it's telling you what it's doing anyway so we've gained that because of doing this it's a D dialog but again just look at the source code to see what it's doing if you need to if you wants to confirm this work first like say you can extract this out to a valuable put a breakpoint in run and then this configuration will look at all configuration providers but the one that the create web default thing added was that app Jason and you can see it's then pulled in the connection string from there and to be really sure you could you know go in and change it to server equals a bunch of dots and then rerun and we should see that we get you know that configuration so you know it's coming from there so now at the point where we are here really this set or people that we've done it ourselves manually and we've gone through every step and you know added them this really is the stage which you would get when you did just make a new MVC project from file new project and then MVC as the web you would naturally get I think it after also add an identity you know an authentication thing but you get a very similar setup to this where you've got your services adding the contacts using the server getting a default connection but now you've done it from scratch you've also done it completely without the dependency injection first to understand what the DB context is doing and that you only need this DB contact I work with entity framework you don't need the dependency injection you don't need any of this you don't need the config file it's self contained in this DB context there's your key but the difference with doing the injection here is mainly or almost entirely for the benefit of them being able to do dependency injection and have this context automatically scoped for you to be created every request and disposed of at the end of every request that's kind of the benefits there as I mentioned that you would not typically do this on every request I've just put that in there for now because we only have one request but we'll talk more about entity framework now going forward anyway in the future videos and we'll start making now the real Fassett Oh words back-end server so the next video will be starting the actual server don't be impractical this kind of layout in there and then we'll actually start adding it users so you can sign up to four set up word and then we can go back to Fassett a word client application and start actually linking in the Windows desktop application with the live website and start doing some really fun things so hopefully this video is useful but as usual any questions or comments just leave them below and I'll get back to you
Info
Channel: AngelSix
Views: 57,579
Rating: undefined out of 5
Keywords: entity framework, entity, framework, core, sql server, sql, transact, ssms, asp.net, c#, mvc, basics, tutorial, server, chat, database, example
Id: bmbeBFfiuck
Channel Id: undefined
Length: 67min 10sec (4030 seconds)
Published: Thu Jan 11 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.