C
C#10mo ago
vileruby

❔ 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
Angius
Angius10mo ago
$genericrepo
Angius
Angius10mo ago
Generic repositories are the wrong pattern to use with EF, yes, since EF itself is a repository already You probably want services if anything
vileruby
vileruby10mo ago
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?
Angius
Angius10mo ago
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()
vileruby
vileruby10mo ago
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?
Angius
Angius10mo ago
No, just to commit all of the changes you made
vileruby
vileruby10mo ago
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...
Angius
Angius10mo ago
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
vileruby
vileruby10mo ago
ok thanks for the help
Accord
Accord10mo ago
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.