Mango.Nop.Libraries/Mango.Nop.Data/docs/REPOSITORIES.md

43 lines
2.2 KiB
Markdown

# Repository Pattern
> Part of `Mango.Nop.Data`. See `Mango.Nop.Data/README.md` for project overview.
> For transaction patterns see `docs/TRANSACTIONS.md`.
## MgDbTableBase\<TEntity\>
Repository base wrapping nopCommerce `EntityRepository<TEntity>`.
**Constructor:**
```csharp
MgDbTableBase(IEventPublisher, INopDataProvider, IShortTermCacheManager, IStaticCacheManager, AppSettings)
```
### Features
| Feature | Detail |
|---|---|
| `GetAll()` | Returns `IQueryable<TEntity>` from `Table` property |
| Automatic timestamps | `ITimeStampCreated.Created` set on insert; `ITimeStampModified.Modified` set on insert/update |
| CRUD hooks | `OnInsert(entity)`, `OnUpdate(entity)`, `OnDelete(entity)` — virtual, overridable |
| Cache clear | `OnUpdate` clears `IStaticCacheManager` (currently clears all — TODO noted in code) |
| All CRUD overrides | Overrides all sync/async `Insert`, `Update`, `Delete` methods to call hooks before `base.*` |
| `DeleteAsync(int entityId)` | Convenience: load by id then delete |
| `DeleteAsync(predicate, bool publishEvent)` | When `publishEvent=true`, loads entities first then deletes with events |
## MgDtoDbTableBase\<TDtoEntity, TMainEntity\>
DTO-aware repository for when the DTO entity (`TDtoEntity`) maps to a different main nopCommerce entity (`TMainEntity`). This is needed because LinqToDB tables are registered for DTOs, but nopCommerce events must fire on the main entity type.
### Features
| Feature | Detail |
|---|---|
| `GetMainEntityById(id)` | Loads `TMainEntity` from `INopDataProvider.GetTable<TMainEntity>()` |
| `DeleteMainEntityById(id)` | Deletes the **main entity** (not the DTO) and publishes `EntityDeletedEvent<TMainEntity>` |
| Delete overrides | **All Delete methods throw** — forces callers to use `DeleteMainEntityById()` instead |
| Event bridging | `EntityInsertedEvent<TDtoEntity>` -> loads main entity -> publishes `EntityInsertedEvent<TMainEntity>` |
| Event bridging | `EntityUpdatedEvent<TDtoEntity>` -> loads main entity -> publishes `EntityUpdatedEvent<TMainEntity>` |
| Event bridging | `EntityDeletedEvent<TDtoEntity>` -> **throws** (must use `DeleteMainEntityById`) |
**Critical rule:** Never call `Delete` on a `MgDtoDbTableBase` repository directly. Always use `DeleteMainEntityById(int id)`.