ASP.NET Core Web API .NET 6 2022 - 4. Installing Entity Framework
HTML-код
- Опубликовано: 13 июл 2024
- ASP.NET Core Web API .NET 6 2022 - 4. Installing Entity Framework
Github Repo For This Project: github.com/teddysmithdev/poke...
Twitter: / teddysmithdev
Github: github.com/teddysmithdev
Linkedin: / teddy-smith-015ba61a3 Хобби
Man, i hate it when people say "just copy paste it" without at least explaining it a little bit. Lets stick to the most important error for this: the seed from the github repo is the FINISHED seed of the project (i assume), which is incompatable with the current status of the project (e.g. reviews suddenly have ratings, owners have first and last names etc). If some1 has trouble with it, either remove incompatabilities from the seed code or add those to the models.
agreed
I agree with that, little bit disappointed as I came for an explanation
yh really poor tutorial tbh. Hes just writing the code and hardly explaining it.
thanks
Thank you for this comment. I thought I was going crazy. Updated the models and redid the migration steps. Got it to work :)
When I ran the Add-Migration InitialCreate command I got an error. I installed the Microsoft.EntityFrameworkCore and the Microsoft.EntityFrameworkCore.Tools nuggets and everything work. You forgot to install those two. All in all the nuggets I have are :
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.Design
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools
Swashbuckle.AspNetCore
Thank you this helped alot
Thx friend, if u don't add this packages u can't seed the database!!!!!
this saved me thank you
gracias amigo!! me ayudaste aquí
THANKS!!!
1:03 Create DB
2:00 Get a connection string
24:11 Finally someone showed me how to find terminal in Visual Studio :)
Lol.......I remember watching this a year ago and thinking "WTF, how am I ever gonna learn this?". Now, I've just popped back to recap on fluent api many to manys. You're a star, Teddy and to anyone else thinking "How the f**k am I gonna learn this?", you WILL understand it. Just keep practicing under the guidance of Don Ted ;)
Beginner here, and I am completely lost, lets see how it goes in one year from now haha
So, how's going?@@ernest1428
@@ernest1428 its been 6 months, hows it going?
@@ronjohnson123 I have stopped my studies due to personal reasons, but I finished some courses and reached some SQL queries with .NET, yet I'm planning on continuing next year the journey
@@ronjohnson123 dude gave up
Your tutorials are really enterprise level, most other content creators don't do this on this level, they'll just give it from a locally perspective, I bet you get into design patterns too 🔥
Teddy, thank you man! You have no idea how helpful I'm finding your content to be!
Man! Binge watching (and coding along!) your content. Simply amazing!!!
This was super helpful. I was searching for over 2 days and here's everything I wanted
OMG Your tips to the databases (connection string) was so amazing. Love you good works, thank you!
Dude.. the SQL Server Object Explorer, total diamond right there. Love the tip!
This is the best explanation of EF core that I have ever seen. Thank you!
Hello Teddy, I really appreciate your effort making these tutorial videos. Your steps really clear and easy to understand. Thank you very much!
this is the best tutorial I've found so far. As another said this is enterprise level and cover a lot of topics. Nice
love your videos! they are very good for begginers ! Thank you so much for this ! 🥰😍
Awsome! thx for this! You are great!
I've spent weeks trying to watch how to connect to database... and everywhere i was getting some kind of error. but with you it was so easy!
Thank you for such a cool tutorial. Keep it up🤓👍
Thank you sir. This is gold!
Really really useful! Thanks !
Decided to load my data directly into the database before starting the application build, SQL is easy and it's so much easier to do this at database level rather than scripting something into the application. But good to see that you've used a different way which will help people who lack SQL skills!
You are perfect! Thank you so much!
Hey man you are the best eish thanks Teddy
so detail. good luck to you !
I had my troubles with the Rating in the Seed file, but I managed to put it in the PokemonReview model class. Nice little test you put in there
it works, I had some issues when running the Add-migration InitialCreate command -- after googling I found that I had the connection string spell wrong, but I made it . I proud of myself.
Thanks for watching hahaha- like teddy said
Thanks for watching 😂
Excellent!new subscriber here
Thank you so much for connection string trick
Thanks Prof
nice way to get a connection string!
But there is simpler way. We can simply connect to server and choose database with connection string from C# level.
Anyway Loved your content,
Have a nice day good man
In this specific scenario, what would be the best way to add additional restrictions to fields? for instance, Max Limit of character of the Country, or the Review integer can only be from 1 to 5?
Pokemon is already plural. SInce (from my long term memory) it actualy stands for Pocket monsters
Amazing!
Guys if you have a problem with your Add-Migration and nothing helps, make sure you delete the stuff in your Controllers folder in solution explorer. I forgot to delete the WeatherForecast default app controller and it messed up my build
For those of you watching who might have trouble hooking up your local server or logging into your local server you have to set "Trust Server Certificate" to "True" when prompted.
Un exito mi amigo Teddy, por favor trata de hacer una aplicacion conjunta de Angular y webApi .netCore, una bien avanzada, como tu sabes! gracias amigo por todo el trabajo que nos brindas. Saludos desde Argentina!
For anyone unable to add the SQL server in Visual Studio with an error that says cannot connect or find the SQL server, your connection name may not be the same as the Name in the property window. Instead, click on the "View Connection Properties" in the Server Properties window, and copy the server name instead. Put that in the "Server name" in the connect window in VS
Thank you, this was so helpful for me. I was facing the same issue and searching for the solution in stackoverflow and all but I couldn't find it. Finally I just went down to the comments and lo and behold! The answer was right there!
Hey, is there a way to manually execute the sql queries instead of using the dbcontext models?
Thank you.. i like this tutorial, actually i'm using as a project for school. just wanna add that there is an easier (for me) way to get the connection string, need just to execute this script >>
select
'data source=' + @@servername +
';initial catalog=' + db_name() +
case type_desc
when 'WINDOWS_LOGIN'
then ';trusted_connection=true'
else
';user id=' + suser_name() + ';password='
end
as ConnectionString
from sys.server_principals
where name = suser_name()
Hello, what is the alternative way if I dont use the Add-Migration? In our task, they say that we need to avoid code first approach with migration.
Great Video so far but why is the screen blurred
thank you for like perfect example, because I search what type project can i write, but in the the create seed, I don't understand why you need it? without it isn't good? we can't write different without seed?
Damn thank you Teddy nice video, but I did use the azure sql database and worked perfectly 🤣
🙌
I use microsoft sql server at my company, I will back up that claim. Good to know it.
hey teddy i have been getting nullrefernceexception everywhere like in models where we set the firstname lastname etc
Are you using SQL Express Core?
If you get an error after doing everything correct, in .csproj file of your project, change the InvariantGlobalization to false
Thank you. It was bugging me
Bro how did you get that connection string from the search bar?
Lets rock with a database
if there is database already..do we need to use migration...pls rply sir
i have a proplem, after doing all the steps well, and after updating the database i fount it generate automatically a column with name OwnerId1 in PokemonOwners table, and a column with name CategoryId1 in PokemonCategory table, and i notice that while adding migration the program tell me that it create those 3 columns in the shadow, i don't know the reason, please could you help me with that!
Question, is there a way to avoid all this DB creation by sharing a database? it is not easier to share a file of a database?
When I copied the seed file from your github I was getting red squiglies under rating for reviews and FirstName and LastName, I don't remember you adding them to the models. Or does this have something to do with the relationships. Maybe I messed up there. IF someone had a similar issue would appreciate any help.
same here, owner does not have first and last name
If facing an error during Add-Migration InitialCreate with build failed then do some changes owner(first name and last name instead of just name ) and review (add ratings)class
I get this error -> The property or navigation 'Category' cannot be added to the entity type 'PokemonCategory' because a property or navigation with the same name already exists on entity type 'PokemonCategory'.
thanks a lot,i have not noticed changes in review :)
Any advice to connect visual studio to sql server running in docker. The sql server object explorer doesn't work and google replies suck
I have right columns in database, however there is no data. In the table Countries I have only empty columns Id and Name. How can I fix this?
can i do this without downloading microsoft SQL ? like doesnt VS have its built in SQL and I have MySQL on my pc as well ?
Hello Teddy, In the DataContext example you have done, there seem to be a composite primary key used and when I was using a singular key i got lost can you provide some guidance
You might need to make sure that you are specifying id as primary key? Never seen that issue before so not sure
Tried running this in .Net 8 but built it using .Net 6. All those warnings you got don't work when you get to a an error in Program line where it's trying to run data. Null exception because all those warnings you have in your classes.
Hello teddy. I am getting the tables but there's no data inside. Every command got executed without any errors. Can you give me a clue as to what might have happened?
For me the ServerName was not same as the Name in the Server Properties, It was in View connection properties where its clearly mentioned ServerName might help someone
👍👍
Teddy i followed ur video and everthing work perfectly but i forgot to add 1model to add 1 more model to the database do i need just update databas? Or add migration again?
Both. Run migration and update database in that order.
If you use an local server like he does you can only type "." (a dot without the strings) insteat of copying the whole name
When i run "Update-Database", only the table names (without the data) is being stored at default database named "main". Does it because i didnt follow your database name which i opted to name it as pokemonDB?
No, you can name your database whatever you like. Chances are you missed the step at 3:34 where you type the server name at the top and then *choose from the Database Name field at the bottom.* From the SQL Server Object Explorer you can probably delete your "main" database and then restart from 2:45
did you add Services.AddTransient(); in program.cs file? i forgot, I encountered the same error.Then I ran the dotnet run seeddata command.
Are the SQL server and SSMS required? Any tips for mac users?
You can use Azure Data Studio with a docker instance. It works almost exactly the same.
18:57 how come you have "Migrtations" folder out of nowhere?
To seed data from the command line: `dotnet run seeddata`
Is seed class same as migration..
So I got everything going good, the only issue I have is that the data is not showing up in the actual local SQL database? I tried to run another Database-Update and it even said No migrations were applied. The database is already up to date. But then I check my database and there isnt anything there?
Make sure you are not checking the “master” db when checking database.
Although tabels are created when migrating, How the data is injected to database??,
do we previously added in db??
can anyone explain me pls
How do you set data context when your model differs from tables you want to use ? How to you use tables with different name than model, and different column names?
You can use annotation to change column names. There is also a builder pattern in DbContext that will allow you to make complex adjustments.
@@TeddySmithDev Hey Teddy, that was faster than a cup of coffee. Surely will explore this.
i cant find the second Pokemonrevapp foulder it just has the initial one
I dont know if the course has been updated, but the seed columns doesn't match with de models. Informations such as Rating, FirstName, Last name in Owner and Review does not exist.
I checked the UML twice and still, seeds does not match.
facing same problem
He updated it. If you check his Github models file you can see the corrected models. only need to change review and owner models slightly
Teddy I have gone through this entire video series and now I am applying that to another project but I stuck In seed file creation. which you have missed although I have tried several ways to create it and created also and when I am done with it is showing tons of error while running the "dotnet run seeddata" command......... please help me
what are the errors? please post github link and I will look
Is onModelcreating method for many to many relationship only?
It's for many things in general, but many to many relationships is one of them
I'm hoping someone sees this but my build fails when i try to Add-migration i tried using -v but that didn't give me any useful info as to why it's failing
I have issue when I run command dotnet run seeddata then it throw "System.ArgumentOutOfRangeException: startIndex cannot be larger than length of string." I don't know why. I try to repeat to see video and follow the code but not work. I still error when seed data. I can migration and update to database success
make sure you add the "builder.Services.AddTransient();"
I don't understand please help me with it:
At the beginning we created a database. Then connected sqlserver with the pokemanreview db. when are are seeding you said there should be no database with same name and we saw in your server management there was no db. I assumed you deleted the pokemonreview database at some point. so what is the deal here? we should also remove the databse from server management app? I successfully add-migration but couldnt update-database? can you help me with that?
Does the migration give an error? It should create with name in connection string but you will get error in console if no success.
I really enjoy this series, but I can't get the connection string hack to work. When right-clicking the database and selecting properties, an empty window comes up.
Might be time to update VS. if you can’t update, I would look into resetting settings to factory default. Never heard of this before 🤔
I also had problems running Add-Migration. In the end I ran the app and fixed the errors, then it worked
How did you solve this i am also having same error
the tutorials are very awesome but the only problem I have is with the lack of explanation with seeding
Thanks for the input 🤔
I am gtting error while adding migration itself, tried hard but couldnt find solution.....
I've created the database and the seed as you shown. When I try to select the rows, the datas that should be there(seed), they're not :(
does it produce error? your database context or settings .cs file is likely culprit
@@TeddySmithDev don't worry, I rebuilt everything from zero and it worked! Thank you, you're Awelsome!
don't forget to run the seeding commands from the terminal cuz I did and thought they ran automatically when u add migration and update the database
I have reached video 5, and after installing the necessary packages, and also written the same code as yours. I am having this error when i run: Add-migration . The errors says Value cannot be null. Parameter('builder'). Please what should I do
Facing the same issue.
@@shiladityamukerji2577so did you solve it?
Can i skip the part of many to many relationship if my database doesn't have it?
yeah actually you probably could
If you're using docker for whatever reason, your connection string may have the password show up as a bunch of *****. Just put in your actual password, should work out fine(if you've followed everything else properly that is).
"you probably didn't need to know that" .... I did, i did need to know that. lol
sucessfully i am able to run my project but data is not get inserted in any table what could be reason for this can anyone please tell me
Man, I'm getting an error on this last step. Does anyone know how to fix it?
Didn't anyone get errors in the seed file. In the seed file provided in teddy's github link, there are firstname and lastname in the owner. But while creating the owner modal, we didnt include them. Did anyone did something about this?
Yeah you need to change the Name to FirstName and LastName
Yeah you need to change it. And update the Review aswell. He integrated a public int Rating
Thanks guys ^
I get this error -> The property or navigation 'Category' cannot be added to the entity type 'PokemonCategory' because a property or navigation with the same name already exists on entity type 'PokemonCategory'.
You may have added the same property to the model
sorry i coppy code file Seed.cs but it error with "review"
How do i do this in VS Code? 2:45
what is this "seed" use for ?
i trying create different theme "not pokemon" but im stuck here
idk what is that seed
Seed = put fake data into DB so you can have something to work with
@@TeddySmithDev i see, so i can skip that step right?
When i run "Update-Database" command I got an error:The ConnectionString property has not been initialized.
why is this error caused, how can i fix it.
Did you fixed it i have the same error and if you did could you explain me too please
same error
if you did it teddy´s way, so make sure you reference the correct key from appsettings.json in your programs.cs. "DefaultConnection" is the key with your ConnectionString, so check options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")) is correct. could be a typo or your autocomplete, messing with you.
Hi, Although I create the seed data in the same way, the database is created, all tables are coming, but the data in the tables are not. What could be the problem here?
You might not have run “dotnet run seeddata”. Need to make sure to add seeddata.
Hey Teddy, I did everything and it worked out perfectly fine. However, when I checked the data for each table everything was correct except the PokemonOwner table. The PokemonOwners have 0's on the PokemonId column but 1,2,3 on the OwnerId. What could be the issue? @@TeddySmithDev
Maybe you will know the problem. I use AzureSQL and when I try to execute migrate I receive error:
The SELECT permission was denied on the object '__EFMigrationsHistory', database 'master', schema 'dbo'.
Currently still figuring out how to grant access to master. But still no hope.
forgot to include category in defaultconnection heh. (dont use default aka master).
You will prob have to go in and set the permissions in SQL
@@TeddySmithDev Thank you for response, anyway, I just used default connection instead what I needed to do was define Catalog. When I defined Catalog= it worked fluently. Thank you for response.
why we need that seed class plz someone explain how it works? do I need to do the same for my own projects?
seed class is used to populate dummy data for your project. You dont really need it but if you want to test your API out then this is one way you could create ''random'' test data :)
Hey, what's wrong with 'Pokemons' in plural? :) What other options?
You can put Pokémons for DbSet. Won’t change anything but spelling. Slight possibility you might get invalid object error but then you just change the table name to what error is giving you.
Adopting a clear and intuitive naming convention for lambda parameters significantly enhances the readability and maintainability of your Entity Framework Core configurations. This approach ensures that anyone reading the code can quickly grasp the relationships between entities, making the codebase more accessible and easier to work with.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity()
.HasKey(pc => new { pc.PokemonId, pc.CategoryId });
modelBuilder.Entity()
.HasOne(pc => pc.Pokemon)
.WithMany(p => p.PokemonCategories)
.HasForeignKey(pc => pc.PokemonId);
modelBuilder.Entity()
.HasOne(pc => pc.Category)
.WithMany(c => c.PokemonCategories)
.HasForeignKey(pc => pc.CategoryId);
modelBuilder.Entity()
.HasKey(po => new { po.PokemonId, po.OwnerId });
modelBuilder.Entity()
.HasOne(po => po.Pokemon)
.WithMany(p => p.PokemonOwners)
.HasForeignKey(po => po.PokemonId);
modelBuilder.Entity()
.HasOne(po => po.Owner)
.WithMany(o => o.PokemonOwners)
.HasForeignKey(po => po.OwnerId);
}