❔ Repository pattern
Creating a tutorial App and I have a EF Core DbContext injected in a a generic Repostitory<T> class. The problem i'm having is I want to be able to save multiple entities at once, but currently due to the Repository pattern it seems I am limited to saving one entity at a time. Am I using the wrong pattern? Is there an established way of handling this scenario?
11 Replies
$genericrepo
Generic repositories are the wrong pattern to use with EF, yes, since EF itself is a repository already
You probably want services if anything
So generally you'd prefer the service class to have the DbContext injected directly? And you would call .Entry on the dbcontext for each entity to update in the method?
You'd inject the dbcontext, yes
And to update a given entity, you'd use
.ExecuteUpdateAsync()
Or, if using an outdated version of .NET and EF, you'd fetch the item, edit it, and .SaveChangesAsync()
I thought that there was a way to save every entity being tracked by the dbcontext in one method call? or do you have to call .ExecuteUpdateAsync on every entity?
No, just to commit all of the changes you made
I see
so in the following example does look correct to you, in the scenario where you are trying to save 2 entities in one go?
private DbContext _context;
public void SaveStudentInfo(Student student, Attendance attendence)
{
_context.student.ExecuteUpdateAsync();
_context.attendance.ExecureUpdateAsync();
}
This is just an example off the top of my head, for learning purposes
Excuse the typo...Basically
With the async being handled properly, but yes
This would still call the db twice, though
I don't think there's any way to update multiple unrelated entities in a single database call
You will either have to do a fetch + update, or two updates
ok thanks for the help
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.