Getting Started with Entity Framework Core in .NET

  Рет қаралды 37,461

Nick Chapsas

Nick Chapsas

Күн бұрын

Check out my courses: dometrain.com
Subscribe to my weekly newsletter: nickchapsas.com
Get the source code: mailchi.mp/dom...
Become a Patreon and get special perks: / nickchapsas
This video is sponsored by AWS. To get $50 free AWS credit, check out this link: aws.amazon.com...
Hello, everybody. I'm Nick, and in this video, I will show you how you can get started with Entity Framework Core in 2025. EF Core is one of the most popular ORMs in .NET and every developer should know how it works.
Workshops: bit.ly/nickwor...
Don't forget to comment, like and subscribe :)
Social Media:
Follow me on GitHub: github.com/Elf...
Follow me on Twitter: / nickchapsas
Connect on LinkedIn: / nick-chapsas
Keep coding merch: keepcoding.shop
#csharp #dotnet

Пікірлер: 74
@flyte24
@flyte24 4 ай бұрын
Excellent as usual. Follow up video needed and should include relationships between entities, and how to define in OnModelCreating etc. , the nuances with .Include() and when to use SplitQuery etc. etc.
@bu113tpr00fp03t
@bu113tpr00fp03t 4 ай бұрын
I'd love to see a deep dive, taking this to the next level. Thanks, Nick. Great content, as usual!
@mikelautensack7351
@mikelautensack7351 4 ай бұрын
Perfect timing! I’m was just going to learn efcore this afternoon!
@learndevtech
@learndevtech 4 ай бұрын
I took the course after this video. I can only say: both are brilliant, this video and the course.
@Trixz79
@Trixz79 4 ай бұрын
The start of ef always looks good. The problems starts when you have a db with lets say order -> orderrow -> item -> unit relations and start to include. At least in old EF you could easy be in a situation where you load order with rows, but then have a foreach loop getting the items and unit one by one. This because of the lazy loading and when new to EF and working on small datasets it's easy to miss and realise when data grows the bad performance you just built. Also navigation properties that relates to each other and when returned creates circular references. When you know sql it feels like learning ef is like learning sql over again but in new syntax. EF code first also "removes" store procedures. Sometimes you would like these to gain certain performance issues I think. So a follow up guide with more depths and relations between tables and tips to avoid the most common pitfalls would be great!
@All-in-on-GME
@All-in-on-GME 4 ай бұрын
These are interesting problems. I've never encountered them. I would recommend using explicit includes via directly calling the property, navigation path and all, instead of implicitly including navigation and then blanket pulling data as a 'select *'. You can even use something like automapper to 'project to' which will behave in that same fashion. The circular references, if I'm not mistaken can be avoided by configuring JSON serialization to ignore JSON cycles. Stored procedures can be added to the up/down, but yes it's manually created migration code. Or you can create the stored proc in db and write a call into db context, oooor you could execute raw SQL using 'FromSql' or 'FromSqlRaw'. I created some pretty cool pipelines by rolling my own generic & dynamic procedure call builder, controlling inputs and outputs with a couple DTOs. All in all, I felt EF Core to be complementary to my SQL. SQL/DB development/BI/ETL is all I knew before stumbling into software development and have felt extremely empowered in EF Core since I started using it about 2 years ago.
@zethoun
@zethoun 4 ай бұрын
as far as I know, you still can activate lazy loading in EFCore (but I never do it, so easy to do something nasty with your performance). as @Cam_all-in-on-GME said, you can use Include() (and .ThenInclude) or, better yet, do projection so the needed include will be used by EFCore and only the needed data will be selected (instead of returning all 25 columns from Order table when you only need the Id) note: with the projection is mainly for readonly queries and if you're really into performance, when doing readonly, you can use FromSqlRaw or combine another ORM like Dapper and write your own, optimized sql queries (EFCore can be really subpar if you have more than 1 include)
@thismotta
@thismotta 12 күн бұрын
You don’t always need both sides of a relationship to reference each other. For instance, if an item can’t exist without an order, the Order entity can hold a collection of items while each Item just stores the order’s ID. Then, you can decide whether to include items in your queries, skip them, or fetch them later. EF Core’s examples might show bidirectional references, but they’re optional. If you need child data, you can use Include/ThenInclude or configure auto-includes. EF isn’t perfect, but once you learn how to set it up correctly and grasp SQL fundamentals-like preventing cartesian explosions-it becomes a powerful ORM. You still have to do some work to match it to your application’s needs, since it can’t automatically cover every scenario.
@jiM3op
@jiM3op 4 ай бұрын
Hi Nick! This is a nice one... A follow up would be appreciated! Thanks so much!
@rainair402
@rainair402 4 ай бұрын
I wanted to say the same. I'm using EF Core, but I wasn't aware of "No tracking" which I would have used before for good reasons.
@noemi.farkas
@noemi.farkas 15 күн бұрын
So goood! Thank you, Nick! 🎊
@foamtoaster9742
@foamtoaster9742 4 ай бұрын
Amazing content ! Love to see more of the beginner focused teaching on yt. Would love a follow up
@leandrostoneshop
@leandrostoneshop 4 ай бұрын
Great intro! I would like suggest how to deal with navigation, foreign keys stuf and etc. It's a hell because the EF's convention 😅
@All-in-on-GME
@All-in-on-GME 4 ай бұрын
I create a TableConstraints.cs Add to override On model creating -- TableConstraints.Configure(modelBuilder) if I have a collection of items, say I have a class called 'MenuItem' and this MenuItem has a list of Ingredients which are needed to cook it, my class for MenuItem has: public virtual ICollection Ingredients { get; set; } = new List Then in my ingredients class, simply adding annotation: [Foreign key("MenuItemId")] public virtual MenuItem MenuItem { get; set; } Should do the trick, but that only works when you are using primary keys of each table as the constraint reference. I use alternate keys and have to specify the constraints so Id just add this to my TableConstraints config I mentioned: modelBuilder.Entity() .HasOne(x => x.MenuItem) .WithMany(y => y.Ingredients) .HasForeignKey(x => x.MenuItemId) .HasPrincipalKey(y => y MenuItemId) Can specify here things like: .OnDelete(DeleteBehavior.Restrict) or cascade Or whether property IsRequired. Again, keep in mind that these can pretty much be handled directly in the EF model using annotations but you have more control in the fluent API.
@andresbran88
@andresbran88 4 ай бұрын
24:18 dbcontext is scoped so the object won't be in memory for future requests
@klrdnbdn9943
@klrdnbdn9943 15 күн бұрын
Thanks Nick!
@Hillgrov
@Hillgrov 2 ай бұрын
I wish you would have added a section about one-to-many relations and many-to-many relations
@CharlesBurnsPrime
@CharlesBurnsPrime 3 ай бұрын
I use your lung form videos as a reference even for technologies that I am already familiar with because you have a certain way of getting to the point, so they are useful references.
@Guillen8606
@Guillen8606 4 ай бұрын
Looking forward to the next one. Thanks
@FatimahAlhamawi-kx7dw
@FatimahAlhamawi-kx7dw 4 ай бұрын
Awesome 😍 keep going I like your content ✨
@valeriesimpleton2525
@valeriesimpleton2525 4 ай бұрын
This is a great intro to efcore. I would like to see the follow-up.
@RohitMoni
@RohitMoni 4 ай бұрын
This was great, thanks for the video!
@dereinzigwahretmx
@dereinzigwahretmx 4 ай бұрын
Hi Nick and everybody interested in this topic! First of all, thanks for that video. It's a great starting point for using EF and in general, I really like the topics you cover in your videos. To return to EF, I'd like to ask a question about your oppinion. I found myself preferring EntityTypeConfiguration over adding attributes directly to the entity classes. It's because I have the feeling to have more control over what's created in the database with it. Also the code of the entity classes is more clean - at least in my point of view. What do you think about EntityTypeConfigurations? What do you use in your production code? This question goes out to you all following this video! Thank you for your answers!
@sheikhquadeer5965
@sheikhquadeer5965 3 күн бұрын
that is what i love in java u just define class object and it will make table from it
@wimlotz713
@wimlotz713 3 ай бұрын
Would love a video on creating relationships.
@mfsbo
@mfsbo 4 ай бұрын
EF core or Dapper does not matter but appreciate EF core basics as it helps juniors to start on this journey and give confidence to seniors. Concepts like seeding data, creating indexes with more organised code and unit testing or stress testing might help people going into large scale projects.
@phillipkatete634
@phillipkatete634 4 ай бұрын
I'd choose dapper over ef core for the sole reason that I can deploy an AOT compiled binary.
@canabale
@canabale 4 ай бұрын
I wouldn't want to see one advanced video on EF-Core. What I'd actually like to see is a deep-dive into certain features like the converter attributes or multi-tenanting approaches.
@JordiC354
@JordiC354 4 ай бұрын
We need a new performance ef core video.
@bulgarian388
@bulgarian388 4 ай бұрын
I actually want to request a beginner and deep dive into PostgreSQL, probably on Dometrain. I've used SQL Server for 15+ years, but I'd like to learn alternatives especially where costs could be reduced.
@Rigal01
@Rigal01 3 ай бұрын
How would you manage transactions with single or multiple contexts? We run a database first database and when savechanges fails, the tracked changes will stay and provoque fails on every subsequent call to saveasync, even from other methods, the only solution is to manually untrack all changes.
@Esgarpen
@Esgarpen 4 ай бұрын
Wasn't it like a year ago you made a video promoting Dapper over EF? 😅 Anyway, always good to know different ways to solve an issue
@nickchapsas
@nickchapsas 4 ай бұрын
I still use Dapper in production but I don’t think that if you use EF Core you’ll be immediately trapped in an underperforming mess
@alanis4AL
@alanis4AL 4 ай бұрын
Teleio video 👍
@tecktonick168
@tecktonick168 4 ай бұрын
Can you show us how to use a sqlproj in a real situation? I believe it was potential to be a great tool, migration can be a nightmare in medium/large projects. I think using dacpac with ef core power tools is more effective, but different opinions makes us better 😊
@miguelgremy
@miguelgremy 3 ай бұрын
On the get all function, since the function return a IEnimerable, is the ToListAsync() necessary ?
@bobbastian760
@bobbastian760 3 ай бұрын
I'm not familiar with Rider. How do you get the definition of a class? When you 'run your API' what are you pressing? If you're doing a basic video please say every step thx.
@jayrigger7508
@jayrigger7508 3 ай бұрын
I almost always push EF core into a repository project, and use mapster to return pocos that have not connection to EF.
@jayrigger7508
@jayrigger7508 3 ай бұрын
The reason is encapsulation and to keep EF in a box
@jayrigger7508
@jayrigger7508 3 ай бұрын
The api controller would get reference to repository and not have any EF using statements etc
@hei4227
@hei4227 4 ай бұрын
hey nick one question. which frontend framework are you using in dometrain? react?angular? or blazor?
@paladincubano
@paladincubano 4 ай бұрын
or vue.js maybe?
@hei4227
@hei4227 4 ай бұрын
@@paladincubano dont know xd
@AbhinavKulshreshtha
@AbhinavKulshreshtha 4 ай бұрын
I had a lot of trouble with PG enums integration with EF core. I ended up running rawsql for any update which had Enum column. What is a best way to integrate it.
@lgaljer
@lgaljer 4 ай бұрын
Could you do pattern designs as a new playlist on your channel? Also how outdated is Blazor playlist on your channel?
@TheAceInfinity
@TheAceInfinity 3 ай бұрын
Why is this project using .NET 9 (rc) and preview language features though for getting started in EF?
@matkeyboard8054
@matkeyboard8054 4 ай бұрын
Why ef core first db call take time how to speed it up , our aws lambda usually timeout
@serhii-kimlyk
@serhii-kimlyk 3 ай бұрын
Any chance microsoft will introduce support for Common Table Expressions in EF? EF is way better then Dapper, in terms of code readability. But things become worse if I need to work with hierarchies. I know there are workarounds for that, but these are workarounds.
@Zashxq
@Zashxq 4 ай бұрын
how does your cli look like that? so pretty
@phizc
@phizc 4 ай бұрын
He's probably using Oh My Posh.
@krccmsitp2884
@krccmsitp2884 4 ай бұрын
looks like oh-my-posh
@martink.7497
@martink.7497 4 ай бұрын
Just in time, with a new project, I'm finally facing the long-feared EF, and so far, so good. But found out some obstacles that, if somebody could help, would be awesome. #1 How do I update only some parts of the entity? Currently, I am fetching the entity, modifying what I need, and then trigger the save. However, that is one more trip (select) needed instead of a simple update. While with db.update(entity), I can avoid it, but that overrides all the entity parts. #2 Having DateTime in the model, how do I update it using DB time (not local time), usually done with a SQL query like NOW() or CURRENT_TIMESTAMP(), but with EF? Any tips are appreciated :)
@ДмитрийКондратенко-б5ь
@ДмитрийКондратенко-б5ь 4 ай бұрын
There is like a 'best practice' to store datetime in DB as UTC time always.
@martink.7497
@martink.7497 4 ай бұрын
@@ДмитрийКондратенко-б5ь There can still be a difference. Lets say that the app that calls insert or update is running on the client PC. How do you know he did not tamper with his PC time? Or even if you have control of that app, NTP is disabled for whatever reason, and the time will slide away. With classic SQL NOW() there is no such possibility.
@All-in-on-GME
@All-in-on-GME 4 ай бұрын
Your #1 is actually shown in this video where Nick changes the year of the movie and only partially updates the record.
@ДмитрийКондратенко-б5ь
@ДмитрийКондратенко-б5ь 4 ай бұрын
@@martink.7497 , I meant that if you use some parameter in the application with the value of the current time and then want to save it to the database, it is better to do this using the datetime.UtcNow property. In addition, I have never done this, but I have seen similar code, you can for example configure a column in the database using the entity framework so that when a new record is created, the value of a Sql function is written to this column, for example GETUTCDATE(), if we are talking about ms sql server. This will shift the responsibility of determining the current UTC time to the database server. If it is located outside of the user's computer, for example on a server, I think you can quite trust this time value.
@martink.7497
@martink.7497 4 ай бұрын
@@All-in-on-GME Not really, he sent the whole entity - id, name and year. EF is just smart about it, that it will update only the changed value, the year in this case, but if, for example, the name was empty, it would overwrite it too. So what if we dont know all the columns and want to update only some? With SQL, just update set column1 = value where id = 1. How to do the same with EF? I tried to pass null values, but it yelled at me that the DB column is not nullable, which is true.
@saymehname
@saymehname 4 ай бұрын
I did not see this video on my subscriptions feed. So strange
@DN-kk6pc
@DN-kk6pc 3 ай бұрын
Be careful with AWS. I created a database following the video's instructions, choosing the "free tier" and got a bill for $12 two weeks later. Upon querying, Amazon sent a link to a help item about "when is free tier not really free". Never again.
@paladincubano
@paladincubano 4 ай бұрын
Hi Nick, I usually use db.Add(model) since the model is already defined as Movie, rather than db.Movies.Add(model), it is any difference in performance or anything in this practice?
@sinanerkan9939
@sinanerkan9939 4 ай бұрын
They’re the same things. One is explicit (db.Movies.Add) and the other is implicit (db.Add). Totally depends on your preference.
@jewelryhopper
@jewelryhopper 4 ай бұрын
Advanced please.
@miroslavmakhruk4102
@miroslavmakhruk4102 2 ай бұрын
IMHO no SQL should be written in C#.
@MrThsmith
@MrThsmith 4 ай бұрын
Wayyyy too much upfront stuff. Just get into efcore… we likely have environments already and want to see efcore
@_OsamaAmir
@_OsamaAmir 4 ай бұрын
why is the aspect ratio messed up
@nickchapsas
@nickchapsas 4 ай бұрын
What do you mean?
@neppe4047
@neppe4047 4 ай бұрын
@@nickchapsas it's fine for me (16:9)
@_OsamaAmir
@_OsamaAmir 4 ай бұрын
​@@nickchapsasit was a youtube bug i reopened the video and it was fine
@cezarpimentel
@cezarpimentel 3 ай бұрын
Dapper is safer and faster. It will always be. Never used and never will use ef.
Getting Started with Dapper in .NET
23:42
Nick Chapsas
Рет қаралды 26 М.
Sigma Kid Mistake #funny #sigma
00:17
CRAZY GREAPA
Рет қаралды 30 МЛН
Quando eu quero Sushi (sem desperdiçar) 🍣
00:26
Los Wagners
Рет қаралды 15 МЛН
Что-что Мурсдей говорит? 💭 #симбочка #симба #мурсдей
00:19
Getting Started with Event Sourcing in .NET
37:07
Nick Chapsas
Рет қаралды 65 М.
139. What Are Your Thoughts on Entity Framework Core vs. Dapper?
21:49
6 Reason to Skip Blazor in 2025
10:15
Deploy & Destroy
Рет қаралды 6 М.
Using EF Core’s Coolest Feature to Audit in .NET
26:06
Nick Chapsas
Рет қаралды 41 М.
AI Is Making You An Illiterate Programmer
27:22
ThePrimeTime
Рет қаралды 298 М.
Brutally honest advice for new .NET Web Developers
7:19
Ed Andersen
Рет қаралды 326 М.
The Logging Everyone Should Be Using in .NET
15:34
Nick Chapsas
Рет қаралды 97 М.
"You're Doing Validation Wrong in .NET" | Code Cop #023
14:44
Nick Chapsas
Рет қаралды 44 М.
Sigma Kid Mistake #funny #sigma
00:17
CRAZY GREAPA
Рет қаралды 30 МЛН