Skip to content
This repository was archived by the owner on Apr 17, 2025. It is now read-only.

Commit a043c10

Browse files
author
Angelo Pirola
committed
Aggiunta documentazione DbContext generics
1 parent b809485 commit a043c10

File tree

1 file changed

+104
-0
lines changed

1 file changed

+104
-0
lines changed
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
# Entity Framework Core DbContext generics methods configuration
2+
3+
4+
## Example entity
5+
6+
In this example, the entity is a data model that implements the *IEntity* interface and has a primary key of type *int*.
7+
8+
```csharp
9+
namespace MyNet6Project;
10+
11+
public class MyEntity : IEntity<int>
12+
{
13+
public int Id { get; set; }
14+
public string Name { get; set; }
15+
public string Description { get; set; }
16+
}
17+
```
18+
19+
20+
## Example interface
21+
22+
In this example, the interface is a service that implements the *IMyService* interface.
23+
24+
```csharp
25+
namespace MyNet6Project;
26+
27+
public interface IMyService
28+
{
29+
Task<List<MyEntity>> GetListItemAsync();
30+
Task<MyEntity> GetItemAsync(int id);
31+
Task CreateItemAsync(MyEntity item);
32+
Task UpdateItemAsync(MyEntity item);
33+
Task DeleteItemAsync(MyEntity item);
34+
}
35+
```
36+
37+
38+
## Example class
39+
40+
In this example, the class is a service that implements the *IMyService* interface.
41+
42+
```csharp
43+
namespace MyNet6Project;
44+
45+
public class MyService : IMyService
46+
{
47+
private readonly IUnitOfWork<MyEntity, int> unitOfWork;
48+
49+
public MyService(IUnitOfWork<MyEntity, int> unitOfWork)
50+
{
51+
this.unitOfWork = unitOfWork;
52+
}
53+
54+
public async Task<List<MyEntity>> GetListItemAsync()
55+
{
56+
var listItem = await unitOfWork.ReadOnly.GetAllAsync();
57+
return listItem;
58+
}
59+
60+
public async Task<MyEntity> GetItemAsync(int id)
61+
{
62+
var item = await unitOfWork.ReadOnly.GetByIdAsync(id);
63+
return item;
64+
}
65+
66+
public async Task CreateItemAsync(MyEntity item)
67+
{
68+
await unitOfWork.Command.CreateAsync(item);
69+
}
70+
71+
public async Task UpdateItemAsync(MyEntity item)
72+
{
73+
await unitOfWork.Command.UpdateAsync(item);
74+
}
75+
76+
public async Task DeleteItemAsync(MyEntity item)
77+
{
78+
await unitOfWork.Command.DeleteAsync(item);
79+
}
80+
}
81+
```
82+
83+
84+
## Registering services at Startup
85+
86+
```csharp
87+
public Startup(IConfiguration configuration)
88+
{
89+
Configuration = configuration;
90+
}
91+
92+
public IConfiguration Configuration { get; }
93+
94+
public void ConfigureServices(IServiceCollection services)
95+
{
96+
//OMISSIS
97+
98+
services.AddDbContextGenericsMethods<MyDbContext>();
99+
100+
//OMISSIS
101+
}
102+
```
103+
104+
<b>Note:</b> You need to replace the <b>MyDbContext</b> value with the actual implementation of your DbContext

0 commit comments

Comments
 (0)