Тёмный

Working With Database Transactions In EF Core 

Milan Jovanović
Подписаться 102 тыс.
Просмотров 21 тыс.
50% 1

Наука

Опубликовано:

 

30 сен 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 115   
@MilanJovanovicTech
@MilanJovanovicTech Год назад
Want to master Clean Architecture? Go here: bit.ly/3PupkOJ Want to unlock Modular Monoliths? Go here: bit.ly/3SXlzSt
@md.redwanhossain6288
@md.redwanhossain6288 5 месяцев назад
A quick tips: if you use DbTransaction abstract class instead of IDbTransaction interface, you can use async methods.
@MilanJovanovicTech
@MilanJovanovicTech 5 месяцев назад
Figured that out recently! But thanks for posting the comment. I'm sure it will help someone.
@zameer.vighio
@zameer.vighio Год назад
Hi Milan can you please make a video on GLOBALIZATION & LOCALIZATION with shared resources in NET CORE 6
@MilanJovanovicTech
@MilanJovanovicTech Год назад
Alright, seems like people wanna see it 😁
@adisilagy
@adisilagy Год назад
+1 this will be great!
@zameer.vighio
@zameer.vighio Год назад
@@MilanJovanovicTech yes, Thanks s lot in advance. May Allah always bless you
@zameer.vighio
@zameer.vighio Год назад
@@MilanJovanovicTech in today's video reminding you about this 'Shared Culture'
@MilanJovanovicTech
@MilanJovanovicTech Год назад
@@zameer.vighio Okay, I see. I added this to my content list. But I can't promise when it'll be released. Won't be soon.
@davidsalazar66
@davidsalazar66 Год назад
Bright screen incoming 🤣🤣 Great video
@MilanJovanovicTech
@MilanJovanovicTech Год назад
I don't wanna hurt your eyes 😅
@JoeMeyer8998
@JoeMeyer8998 Год назад
Instead of putting rollback into a try/catch you could also implement a Dispose method the calls rollback if the initial BeginTransaction has not been commited yet. So when the transaction goes out of scope without being commited, Roolback ist called automagically. If you'd want nested transactions you can implement a NumberOfOpenTransactions counter
@mrwalkan
@mrwalkan Год назад
can you give more insight on your saying.
@MilanJovanovicTech
@MilanJovanovicTech Год назад
The Transaction object will also call Rollback in its Dispose method. However, I don't like this implicit behavior and prefer to make it explicit with a try/catch block.
@JoeMeyer8998
@JoeMeyer8998 Год назад
@@MilanJovanovicTech So if Rollback is already being executed in a Dispose method anyway, what's the use of having to call it implicitely? No offense, Milan, but IMHO the try/catch/Rollback are unneeded, even introduce redundant code, and therefore should be removed for the sake of simplicity and good readability. The using statement already tells the reader explicitely that unmanaged resources (in this case the transaction) are freed when the using block goes out of the scope
@MilanJovanovicTech
@MilanJovanovicTech Год назад
@@JoeMeyer8998 There was an issue you could run into if you don't rollback manually. I'm trying to find the documentation link I ran into for reference, but can't find it at the moment :(
@ezecel9
@ezecel9 3 месяца назад
public async Task BeginTransaction(Func action, IsolationLevel isolationLevel = IsolationLevel.ReadCommitted) { using (var transaction = _dbContext.Database.BeginTransaction(isolationLevel)) { try { await action(); await transaction.CommitAsync(); } catch (Exception) { transaction.Rollback(); throw; } } }
@nafisrahman5791
@nafisrahman5791 Год назад
I Appreciate the bright screen warnings lol
@MilanJovanovicTech
@MilanJovanovicTech Год назад
I do too 😂
@davidsantacruz7195
@davidsantacruz7195 Год назад
Great job Milan. I'm not a big fan of EF. Please consider making a video about transactions with Dapper.
@MilanJovanovicTech
@MilanJovanovicTech Год назад
It's even simple with Dapper really, but sure thing 😁
@cheeseburger1884
@cheeseburger1884 Год назад
Thanks Milan! The debugging part is really the cherry on top of an already delicious cake. You are very good at this, I'm proud I found this channel. Your content is gold mate, I'm having a lot of fun =)
@MilanJovanovicTech
@MilanJovanovicTech Год назад
Thank you, I'm happy to hear that
@baebcbcae
@baebcbcae 11 месяцев назад
it's not all, you didn't cover read committed, no need to have a couple of saves for that scenario, just do the validation for some uniqueness and make one save, call this logic concurrently and you'll be surprised =)
@MilanJovanovicTech
@MilanJovanovicTech 11 месяцев назад
Maybe in another video
@baebcbcae
@baebcbcae 11 месяцев назад
@@MilanJovanovicTech I have just struggled with this whole night, transaction scope with serializable isolation level helped
@pilotboba
@pilotboba Год назад
Rather than switching to "bright screen" SSMS you can also use the SQL Server tools built into visual studio to run queries and show data. :)
@MilanJovanovicTech
@MilanJovanovicTech Год назад
You have a good point there! Thing is, I never used it. So the idea didn't even cross my mind.
@alekseis7907
@alekseis7907 Год назад
Thank you! It would be great if you tell more about isolation levels in one of your next video!
@MilanJovanovicTech
@MilanJovanovicTech Год назад
I think it's something people rarely think about, and even fewer people understand. I'll consider it though!
@MTSightseeing
@MTSightseeing Год назад
CAN YOU SHARE YOUR GATHERLY GITHUB REPOSITORY need a project structure please
@MilanJovanovicTech
@MilanJovanovicTech Год назад
It's available on my Patreon
@MTSightseeing
@MTSightseeing Год назад
@@MilanJovanovicTech any other resource without paying money
@zaharivaklinov
@zaharivaklinov Год назад
Nicely put. I had an idea what transactions are used for and have only ever seen 1-2 implementations of them, but with debugging them in this video I understood them more.
@MilanJovanovicTech
@MilanJovanovicTech Год назад
Glad I helped you understand the concept better :)
@nguyentoan2002
@nguyentoan2002 Год назад
I have trouble in this bug "System.InvalidOperationException: 'A second operation was started on this context instance before a previous operation completed", I mean I just executed transaction for the first time but the second was not
@MilanJovanovicTech
@MilanJovanovicTech Год назад
You have to commit or rollback a transaction before creating a new one
@vasilemoraru89
@vasilemoraru89 Год назад
Thanks Milan! My question is regarding "BeginTransaction()" method and it return type. You are telling at the end, that is possible to return a different type to expose less methods. Could you give a code example, because i did not understood this point. Thanks !!!
@MilanJovanovicTech
@MilanJovanovicTech Год назад
The DbContext stores a 'CurrentTransaction' instance internally. You can just wrap the calls to BeginTrasaction/CommitTransaction, and don't need to return the transaction instance.
@vadymivanenko8591
@vadymivanenko8591 Год назад
I've noticed, you're using EF's entities as your domain model. There is a kind of implicit dependency on EF because EF applies some constraints on how we should design our entities (additional constructors, setters, etc.). Is it practical to don't use EF's entities inside a domain model? Which way do you recommend?
@MilanJovanovicTech
@MilanJovanovicTech Год назад
I've done it like this many times before, and didn't have a problem. With EF's fluent configuration you can get around most issues with encapsulating a domain model. You can have two separate models, one for the domain and one for EF, but I find it cumbersome to have to maintain two models if I can get by with just one.
@mocococo2877
@mocococo2877 Год назад
Great work. Thank you. One question I have on your code. After if (attendeeResult.IsSuccess) should you not put "else" and inside it to roll back the transaction ? I mean if it is all or nothing. Thank you.
@MilanJovanovicTech
@MilanJovanovicTech Год назад
It'll be rolled back when disposed
@milosmilovanovic3618
@milosmilovanovic3618 Год назад
If any of the savechanges fail, we would then go to rollback in the catch block? Thanks for an amazing explanation as always!
@MilanJovanovicTech
@MilanJovanovicTech Год назад
Yes, that's how it works
@welfas4580
@welfas4580 Год назад
Hi, Is it common to share transactions between different contexts? Or every context have your transaction life?
@MilanJovanovicTech
@MilanJovanovicTech Год назад
Each context (assuming it's a different type) will have it's own connection to the DB and thus a different transaction
@Tolmachovtv
@Tolmachovtv 8 месяцев назад
Awesome video, way to go! Thanks for bright screen notification )😃
@MilanJovanovicTech
@MilanJovanovicTech 8 месяцев назад
My pleasure 😊
@tomekbednarek2672
@tomekbednarek2672 8 месяцев назад
Don't you think it would be a good idea to also have the read operations within the transaction? Having a more strict isolation level, the read rows would also be locked by the db to make the whole method atomic from the perspective of the db.
@MilanJovanovicTech
@MilanJovanovicTech 8 месяцев назад
Sure, if we set the isolation level so some of the more restrictive values
@icemanja
@icemanja Год назад
Great video! Based on what you demonstrated do you need to use rollback if the update won’t execute without the commit being triggered?
@MilanJovanovicTech
@MilanJovanovicTech Год назад
If the commit isn't triggered, then it's like there were no changes applied to the database. So there's nothing to rollback.
@100valiant
@100valiant Год назад
@@MilanJovanovicTech so then what is the purpose of rollback transaction 🤔
@vidasalud9275
@vidasalud9275 Год назад
Thanks Milan.. Do you have any DDD course with Dapper?
@MilanJovanovicTech
@MilanJovanovicTech Год назад
I don't at the moment
@mustafaahmed7296
@mustafaahmed7296 9 месяцев назад
I have a problem with this, rolling back is not working and changes are not reverted. not sure what's the reason
@MilanJovanovicTech
@MilanJovanovicTech 9 месяцев назад
How can it not work?
@andresperalta2837
@andresperalta2837 11 месяцев назад
Hello excellent video, out of curiosity you have the link to github, greetings from Colombia.
@MilanJovanovicTech
@MilanJovanovicTech 11 месяцев назад
github.com/m-jovanovic
@andresperalta2837
@andresperalta2837 11 месяцев назад
Thank you very much, I am doing a course and your tutorials are my lifeline.
@stavrosk.3773
@stavrosk.3773 Год назад
Great content. Very happy to have discovered your channel. Keep up the good work!
@MilanJovanovicTech
@MilanJovanovicTech Год назад
Welcome aboard! And you can expect more great things in the future 😁
@lemueljohnerispe2741
@lemueljohnerispe2741 Год назад
Is it safe to use this Transaction in every process that is related to database?
@MilanJovanovicTech
@MilanJovanovicTech Год назад
It's unnecessary for simple changes. But yes, it's safe.
@sankarroychowdhury4655
@sankarroychowdhury4655 6 месяцев назад
Milan, how to handle deadlock situation due to transaction block
@MilanJovanovicTech
@MilanJovanovicTech 6 месяцев назад
Where do you expect a deadlock?
@alfonsdeda8912
@alfonsdeda8912 Год назад
Hi Milan, I have done your same thing with unit of work and injected dbcontext and other services that I use in my project, for dependency injection i have used autofac and registered dbcontext as InstanceForLifetimeScope so all injected services in my unit of work capture the same dbcontext, because every service inject dbcontext, all works if I do begintransaction the first time, but if I want to do again i get exception that dbcontext has already a transaction, shouldn't be disposed automatically with autofac or at least the transaction.commit() close the transaction, what if I want to get new transaction every request and not keeping the old? Thanks in advance. I hope i was clear.
@MilanJovanovicTech
@MilanJovanovicTech Год назад
You must've done something wrong, since the transaction should be disposed along with the DbContext
@alfonsdeda8912
@alfonsdeda8912 Год назад
I inject unit of work in form and I want to use every time that I press the save button, that can be pressed multiple times, but every time I need to create new transaction, if I do like you did the previous transaction is not disposed and I get the exception that the transaction has already been started, how can I fix that? Thanks in advance.
@nguyentoan2002
@nguyentoan2002 Год назад
It is the same for me..
@abhinavsrivastava2128
@abhinavsrivastava2128 2 месяца назад
There is a subtle problem with the implementation. The get gathering by id call is still a separate transaction (since every sql statement is treated as an implicit transaction, in case we dont specify explicitly) and in case of concurrent writes, it might lead to the invitation object becoming stale by the time we try to write to db. Obviously it will throw and the catch clause would ensure graceful exits but we can improve the number of failed writes by having the read call within the same transaction in which we are writing. Please let me know ur thoughts... also nice video.. cheers 😊😊
@MilanJovanovicTech
@MilanJovanovicTech 2 месяца назад
| Obviously it will throw Only if we have optimistic concurrency. The default isolation level is ReadUncommitted, which doesn't lock rows in a transaction - so that won't help with the first query.
@abhinavsrivastava2128
@abhinavsrivastava2128 2 месяца назад
@@MilanJovanovicTech no, the default isolation level for postgres is ReadCommitted which uses exclusive locks during writes
@GiorgiChikovani_FromGeorgia
@GiorgiChikovani_FromGeorgia 2 месяца назад
Thanks for a video. Very necessary Topic 🙌
@MilanJovanovicTech
@MilanJovanovicTech 2 месяца назад
Glad it was helpful!
@lamayig8483
@lamayig8483 Год назад
your code Theme color is attractive please tel me the name
@MilanJovanovicTech
@MilanJovanovicTech Год назад
VS dark theme + ReSharper syntax highlighting
@gerezd2335
@gerezd2335 Год назад
What happens if the catch block with the Rollback() call doesn't exist and an exception is thrown?
@MilanJovanovicTech
@MilanJovanovicTech Год назад
The transaction should roll itself back when it's disposed, but I like to make things explicit
@gerezd2335
@gerezd2335 Год назад
@@MilanJovanovicTech Thanks!
@pietropivavieira7988
@pietropivavieira7988 Год назад
Great video Milan! Keep it up with the good work!
@MilanJovanovicTech
@MilanJovanovicTech Год назад
Thanks, will do!
@MrEkwador
@MrEkwador Год назад
Very good tutorial👏🏻! I am still wondering how to handle the transaction when dealing with several different data repositories. How to pass a subset of the repositories selected in a given context and validate it at the end?
@MilanJovanovicTech
@MilanJovanovicTech Год назад
If they all share the same DbContext, they will also share the transaction
@MrEkwador
@MrEkwador Год назад
@@MilanJovanovicTech I was thinking of the case when repositories have different databases and therefore different contexts.
@MilanJovanovicTech
@MilanJovanovicTech Год назад
@@MrEkwador You can't - without a distributed transaction
@BeyondAppearances-0
@BeyondAppearances-0 Год назад
Thanks Milan., But i don't see what the RollBack is actually for, since anyway as long as we haven't reached the transaction.Commit(), nothing is written in the database ? Could you please detail that point ?
@MilanJovanovicTech
@MilanJovanovicTech Год назад
For closing the transaction, and reverting any partial changes. For example, you could have a few SaveChanges calls in a single transaction. And those changes should be visible to queries in the same transaction.
@BeyondAppearances-0
@BeyondAppearances-0 Год назад
@@MilanJovanovicTech Thanks Milan, but how could those SaveChanges affect the Database whereas the transaction.Commit() has not been done ?
@S3Kglitches
@S3Kglitches Год назад
So now the real issue: How to commit it async? I am using TransactionScope which can wrap multiple DbContext instances on the same connection string but there is this issue - the async version of the commit call is not available.
@MilanJovanovicTech
@MilanJovanovicTech Год назад
You can't, it doesn't have an async API
@S3Kglitches
@S3Kglitches Год назад
@@MilanJovanovicTech Then is there a workaround you suggest e.g. with Task.Run()? Do you think it is a good idea? I am thinking of a server process doing these transactions, that might be a real bottleneck when it's blocking calls.
@S3Kglitches
@S3Kglitches Год назад
@@MilanJovanovicTech I am surprised to have found DbTransaction.CommitAsync on microsoft online documentation :D
@MilanJovanovicTech
@MilanJovanovicTech Год назад
@@S3Kglitches Only for EF Core's transaction as far as I'm aware 🤔
@patrickbrown5141
@patrickbrown5141 Год назад
Thank you, very informative 👍
@MilanJovanovicTech
@MilanJovanovicTech Год назад
Glad it was helpful!
@fxri3637
@fxri3637 Год назад
great video!!
@MilanJovanovicTech
@MilanJovanovicTech Год назад
Thank you!!
@mateuszkaleta1495
@mateuszkaleta1495 Год назад
Is it not better to use transaction Scope?
@MilanJovanovicTech
@MilanJovanovicTech Год назад
It doesn't support async operations - but otherwise, works fine. Note however that the transaction isn't committed until TransactionScope is dispoed
@mateuszkaleta1495
@mateuszkaleta1495 Год назад
@@MilanJovanovicTech when You will enable transactionScopeAsyncFlowOption it will works, additionally if I will have for example 5 repositories instances (for example I will call methods from injected classes) I don't care about it, just all saveChanges taken to one Transaction. I'm just wondering if TransactionScope is more elastic solution. (Of course all depends :) but what do You think?)
@arjundate
@arjundate Год назад
Thanks Milan...!
@MilanJovanovicTech
@MilanJovanovicTech Год назад
You're welcome :)
@AmirHashemZadeh
@AmirHashemZadeh Год назад
it was useful :)
@MilanJovanovicTech
@MilanJovanovicTech Год назад
Glad to hear that!
@anushkashan492
@anushkashan492 Год назад
I like al of your series, I'm in the industry almost for 8 years, I rarely seen people doing videos with good content. Very informative. Keep it up buddy.
@MilanJovanovicTech
@MilanJovanovicTech Год назад
I'm humbled to hear that! 💌
Далее
11 ming dollarlik uzum
00:43
Просмотров 1,3 млн
The Unit of Work Design Pattern Explained
12:37
Просмотров 24 тыс.
One to Many Relationship with Dapper & .NetCore 5
40:58
Microservices with Databases can be challenging...
20:52
Common mistakes in EF Core - Jernej Kavka - NDC Oslo 2023
1:03:43
Don't Use Polly in .NET Directly. Use this instead!
14:58
Binary Search Algorithm in C#
17:06
Просмотров 6 тыс.
CED: часть 1
23:37
Просмотров 66 тыс.
I used to hate QR codes. But they're actually genius
35:13
😍Самый ПРИЯТНЫЙ Айфон🔥
0:34
Просмотров 539 тыс.
Playstation 2 в квадрате || Anbernic RG Cube
13:03