amichai
amichai

Reputation: 728

Multiple queries with Entity Framework in C#

I am using C# and EF to work with a SQL Server database.

I need to do several queries at a time. For now I'm doing all the operations together and in the end I'm calling the DbContext.SaveChanges function to apply all the changes at once.

My problem is that if one of the queries has an error, all the queries are cancelled.

Do I need to call the DbContext.SaveChanges for every query for this?

Thanks

Upvotes: 0

Views: 918

Answers (3)

Amit Joshi
Amit Joshi

Reputation: 16389

DBcontext works as UnitOfWork. It keeps track of all the changes in current DBContext and when you call SaveChanges it figures out what exactly should be done while writing those to database. In other words, this is similar to Database Transaction.

Do I need to call the DbContext.SaveChanges for every query for this?

It depends. You need to identify your UnitOfWork. In web applications, it is generally "DBConstext per Request". It may not be exactly for you. Identify group of DB actions those should be done in one group OR should fail as a group. Then call SaveChanges accordingly.

Calling SaveChanges for each DB call may not be efficient. You are ignoring other important features of ORM those will not be helpful in this case. Take a time to identify your UnitOfWork.

Upvotes: 2

jalil
jalil

Reputation: 95

if you don't need transaction then you need to call the DbContext.SaveChanges for every query.

Upvotes: 1

Aniket Sharma
Aniket Sharma

Reputation: 1020

Yes you can call the DBcontext.SaveChanges after every query to run the query successfully. If your one of the query having error so the remain work will be saved and please try to put your error query at the end of your execution if there are no dependency.

Upvotes: 0

Related Questions