From 2a29bf3b4c65d586f9d0a6bae994a54dfc4d41dd Mon Sep 17 00:00:00 2001 From: Patrick BRUGIERE Date: Sun, 17 Mar 2024 11:31:51 +0100 Subject: [PATCH 1/6] =?UTF-8?q?Mise=20=C3=A0=20jour=20de=20'README.md'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/README.md b/README.md index fdcd981..1d7b59a 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,7 @@ # SAE 2A Anglais Ce projet vise à faciliter l'apprentissage de l'anglais dans le cadre d'études supérieures grâce à un site internet et une application mobile. + ## Exécuter localement Clonez le projet @@ -18,6 +19,15 @@ Allez dans le répertoire Suivez les différentes instructions suivant la partie que vous souhaitez lancer. +### EF et WebAPI + +Bonjour cette partie a été réalisé par Patrick Brugière seul. + +Le .sln se trouve dans le repertoir Project/EntityFramework +Il est normalement précisé dans le nom de des test à quelle partie ils appartiennent + + + ### PHP Changez de branche From 4dd9ce51ce40b07c11c6660e53506067a5702646 Mon Sep 17 00:00:00 2001 From: Patrick BRUGIERE Date: Sun, 17 Mar 2024 11:33:20 +0100 Subject: [PATCH 2/6] =?UTF-8?q?Mise=20=C3=A0=20jour=20de=20'README.md'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 1d7b59a..f7571b8 100644 --- a/README.md +++ b/README.md @@ -23,8 +23,9 @@ Suivez les différentes instructions suivant la partie que vous souhaitez lancer Bonjour cette partie a été réalisé par Patrick Brugière seul. -Le .sln se trouve dans le repertoir Project/EntityFramework -Il est normalement précisé dans le nom de des test à quelle partie ils appartiennent +Le .sln se trouve dans le repertoir Project/EntityFramework + +Il est normalement précisé dans le nom de des tests à quelles parties ils appartiennent From e748a047be52b02c32417eb1eb1ac17de10e994b Mon Sep 17 00:00:00 2001 From: Patrick BRUGIERE Date: Sun, 17 Mar 2024 11:48:35 +0100 Subject: [PATCH 3/6] =?UTF-8?q?Mise=20=C3=A0=20jour=20de=20'README.md'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f7571b8..1c8c32d 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ Le .sln se trouve dans le repertoir Project/EntityFramework Il est normalement précisé dans le nom de des tests à quelles parties ils appartiennent - +Pour utiliser un jeton JWT dans l'en-tête "Authorize", il suffit d'entrer simplement sa valeur, sans mettre ni guillemets ni le mot "Bearer" avant. ### PHP From 9b240261045d64d68fc48c296c3379c6643e163e Mon Sep 17 00:00:00 2001 From: "patrick.brugiere" Date: Wed, 27 Mar 2024 17:10:33 +0100 Subject: [PATCH 4/6] push dockerfile --- Project/EntityFramework/.dockerignore | 30 ++++++++++++++++++++++++++ Project/EntityFramework/API/Dockerfile | 30 ++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 Project/EntityFramework/.dockerignore create mode 100644 Project/EntityFramework/API/Dockerfile diff --git a/Project/EntityFramework/.dockerignore b/Project/EntityFramework/.dockerignore new file mode 100644 index 0000000..fe1152b --- /dev/null +++ b/Project/EntityFramework/.dockerignore @@ -0,0 +1,30 @@ +**/.classpath +**/.dockerignore +**/.env +**/.git +**/.gitignore +**/.project +**/.settings +**/.toolstarget +**/.vs +**/.vscode +**/*.*proj.user +**/*.dbmdl +**/*.jfm +**/azds.yaml +**/bin +**/charts +**/docker-compose* +**/Dockerfile* +**/node_modules +**/npm-debug.log +**/obj +**/secrets.dev.yaml +**/values.dev.yaml +LICENSE +README.md +!**/.gitignore +!.git/HEAD +!.git/config +!.git/packed-refs +!.git/refs/heads/** \ No newline at end of file diff --git a/Project/EntityFramework/API/Dockerfile b/Project/EntityFramework/API/Dockerfile new file mode 100644 index 0000000..805b7e8 --- /dev/null +++ b/Project/EntityFramework/API/Dockerfile @@ -0,0 +1,30 @@ +#See https://aka.ms/customizecontainer to learn how to customize your debug container and how Visual Studio uses this Dockerfile to build your images for faster debugging. + +FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base +USER app +WORKDIR /app +EXPOSE 8080 +EXPOSE 8081 + +FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build +ARG BUILD_CONFIGURATION=Release +WORKDIR /src +COPY ["API/API.csproj", "API/"] +COPY ["DTOToEntity/DTOToEntity.csproj", "DTOToEntity/"] +COPY ["DbContext/DbContextLib.csproj", "DbContext/"] +COPY ["Entities/Entities.csproj", "Entities/"] +COPY ["DTO/DTO.csproj", "DTO/"] +COPY ["StubbedContext/StubbedContextLib.csproj", "StubbedContext/"] +RUN dotnet restore "./API/./API.csproj" +COPY . . +WORKDIR "/src/API" +RUN dotnet build "./API.csproj" -c $BUILD_CONFIGURATION -o /app/build + +FROM build AS publish +ARG BUILD_CONFIGURATION=Release +RUN dotnet publish "./API.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false + +FROM base AS final +WORKDIR /app +COPY --from=publish /app/publish . +ENTRYPOINT ["dotnet", "API.dll"] \ No newline at end of file From 5f00cd91f49c6a86d5f2ea98c05c04e2d912c4d4 Mon Sep 17 00:00:00 2001 From: "patrick.brugiere" Date: Wed, 27 Mar 2024 17:12:48 +0100 Subject: [PATCH 5/6] ajout dockerfile --- Project/EntityFramework/API/API.csproj | 3 ++ Project/EntityFramework/API/API.csproj.user | 2 +- .../API/Properties/launchSettings.json | 45 ++++++++++++------- 3 files changed, 32 insertions(+), 18 deletions(-) diff --git a/Project/EntityFramework/API/API.csproj b/Project/EntityFramework/API/API.csproj index 3a41951..0a29e7c 100644 --- a/Project/EntityFramework/API/API.csproj +++ b/Project/EntityFramework/API/API.csproj @@ -5,6 +5,8 @@ enable enable $(MSBuildProjectDirectory) + 1540d456-1696-425e-b511-611542ce7c5e + Linux @@ -17,6 +19,7 @@ runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/Project/EntityFramework/API/API.csproj.user b/Project/EntityFramework/API/API.csproj.user index 031db34..6e2004e 100644 --- a/Project/EntityFramework/API/API.csproj.user +++ b/Project/EntityFramework/API/API.csproj.user @@ -1,7 +1,7 @@  - https + Docker MvcControllerEmptyScaffolder root/Common/MVC/Controller diff --git a/Project/EntityFramework/API/Properties/launchSettings.json b/Project/EntityFramework/API/Properties/launchSettings.json index 87920c5..4aebf86 100644 --- a/Project/EntityFramework/API/Properties/launchSettings.json +++ b/Project/EntityFramework/API/Properties/launchSettings.json @@ -1,33 +1,24 @@ -{ - "$schema": "http://json.schemastore.org/launchsettings.json", - "iisSettings": { - "windowsAuthentication": false, - "anonymousAuthentication": true, - "iisExpress": { - "applicationUrl": "http://localhost:32547", - "sslPort": 44345 - } - }, +{ "profiles": { "http": { "commandName": "Project", - "dotnetRunMessages": true, "launchBrowser": true, "launchUrl": "swagger", - "applicationUrl": "http://localhost:5124", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" - } + }, + "dotnetRunMessages": true, + "applicationUrl": "http://localhost:5124" }, "https": { "commandName": "Project", - "dotnetRunMessages": true, "launchBrowser": true, "launchUrl": "swagger", - "applicationUrl": "https://localhost:7013;http://localhost:5124", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" - } + }, + "dotnetRunMessages": true, + "applicationUrl": "https://localhost:7013;http://localhost:5124" }, "IIS Express": { "commandName": "IISExpress", @@ -36,6 +27,26 @@ "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } + }, + "Docker": { + "commandName": "Docker", + "launchBrowser": true, + "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/swagger", + "environmentVariables": { + "ASPNETCORE_HTTPS_PORTS": "8081", + "ASPNETCORE_HTTP_PORTS": "8080" + }, + "publishAllPorts": true, + "useSSL": true + } + }, + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:32547", + "sslPort": 44345 } } -} +} \ No newline at end of file From 7c08ed82357eb0d32ef84c00b18960ba922797fb Mon Sep 17 00:00:00 2001 From: PATRICK Date: Sun, 31 Mar 2024 23:38:55 +0200 Subject: [PATCH 6/6] switch --- Project/EntityFramework/API/API.csproj.user | 5 +- .../API/Controllers/RoleController.cs | 4 +- .../API/Controllers/TranslateController.cs | 4 +- .../API/Db.in_english_please.db | Bin 106496 -> 106496 bytes .../API/Db.in_english_please.db-shm | Bin 0 -> 32768 bytes .../API/Db.in_english_please.db-wal | Bin 0 -> 41232 bytes .../DTOToEntity/GroupService.cs | 49 +-- .../DTOToEntity/LangueService.cs | 25 +- .../DTOToEntity/RoleService.cs | 33 +- .../DTOToEntity/TranslateService.cs | 27 +- .../DTOToEntity/UserService.cs | 34 +- .../DTOToEntity/VocabularyListService.cs | 31 +- .../DTOToEntity/VocabularyService.cs | 29 +- .../EntityFramework/DbContext/SAEContext.cs | 5 - .../StubbedContext/GenericRepository.cs | 169 ++++++++++ ....cs => 20240331212614_newMigs.Designer.cs} | 10 +- ...6_newMigs.cs => 20240331212614_newMigs.cs} | 82 ++--- .../Migrations/StubbedContextModelSnapshot.cs | 8 +- .../StubbedContext/UnitOfWork.cs | 197 +++++++++++ Project/EntityFramework/TU/GroupTU.cs | 26 -- Project/EntityFramework/TU/RoleTU.cs | 20 +- Project/EntityFramework/TU/TranslateTU.cs | 33 -- .../EntityFramework/TU/VocabularyListTU.cs | 37 --- Project/EntityFramework/TU/VocabularyTU.cs | 37 --- .../EntityFramework/TestConsole/Program.cs | 305 +++++++++--------- 25 files changed, 703 insertions(+), 467 deletions(-) create mode 100644 Project/EntityFramework/API/Db.in_english_please.db-shm create mode 100644 Project/EntityFramework/API/Db.in_english_please.db-wal create mode 100644 Project/EntityFramework/StubbedContext/GenericRepository.cs rename Project/EntityFramework/StubbedContext/Migrations/{20240316154336_newMigs.Designer.cs => 20240331212614_newMigs.Designer.cs} (98%) rename Project/EntityFramework/StubbedContext/Migrations/{20240316154336_newMigs.cs => 20240331212614_newMigs.cs} (85%) create mode 100644 Project/EntityFramework/StubbedContext/UnitOfWork.cs diff --git a/Project/EntityFramework/API/API.csproj.user b/Project/EntityFramework/API/API.csproj.user index 6e2004e..448f454 100644 --- a/Project/EntityFramework/API/API.csproj.user +++ b/Project/EntityFramework/API/API.csproj.user @@ -1,8 +1,11 @@  - Docker + https MvcControllerEmptyScaffolder root/Common/MVC/Controller + + ProjectDebugger + \ No newline at end of file diff --git a/Project/EntityFramework/API/Controllers/RoleController.cs b/Project/EntityFramework/API/Controllers/RoleController.cs index c448c0d..eac740f 100644 --- a/Project/EntityFramework/API/Controllers/RoleController.cs +++ b/Project/EntityFramework/API/Controllers/RoleController.cs @@ -41,7 +41,7 @@ namespace API.Controllers } [HttpGet("{id}")] - public async Task> GetRole(int id) + public async Task> GetRole(long id) { try { @@ -80,7 +80,7 @@ namespace API.Controllers } [HttpDelete("{id}")] - public async Task> DeleteRole(int id) + public async Task> DeleteRole(long id) { try { _logger.LogInformation("Deleting a role with id : {id}", id); diff --git a/Project/EntityFramework/API/Controllers/TranslateController.cs b/Project/EntityFramework/API/Controllers/TranslateController.cs index da08816..73ae8e9 100644 --- a/Project/EntityFramework/API/Controllers/TranslateController.cs +++ b/Project/EntityFramework/API/Controllers/TranslateController.cs @@ -40,7 +40,7 @@ namespace API.Controllers } } [HttpGet("{id}")] - public async Task> GetTranslate(int id) + public async Task> GetTranslate(long id) { try { _logger.LogInformation("Getting a Translate with id {id}", id); @@ -76,7 +76,7 @@ namespace API.Controllers } [HttpDelete("{id}")] - public async Task> DeleteTranslate(int id) + public async Task> DeleteTranslate(long id) { try { _logger.LogInformation("Deleting a Translate with id : {id}", id); diff --git a/Project/EntityFramework/API/Db.in_english_please.db b/Project/EntityFramework/API/Db.in_english_please.db index 867cda464484e9b5daaaa5d48fa524f7dbba6b35..51c2e57ff6382d69789edc080d7c67dc7f3f3a68 100644 GIT binary patch delta 1619 zcmeHHOH30{6rDRWo#~rt`&vI83Ifw@sk)SMJGr^O8Ov3qOqv> z*%>Es+!0-9;xCady3vG%iAJLf<3baouGPeaF(Lk6r8jFA!Lt@By!S?w`a(jADs&8~Kl^JgzAS1-=iGbgns)Myg zle0palw6|H)&{5L+;c7sG;@n14#W&LKo3ijMup%vu+UtHJy#FO`lG|LsMOZNq+)e4 zulT&9fy8pFr%kftu+V8==O~8c+=lukQBf2)U7y?MyjTGCN-K)Mjm9@57)PY;aFtV3 zLLoTrn+Ha0AYyw zr`ZON*L91*AMk7Z5 zZ~;`rp5Dw43xGc{_*2d|^A7tMh64^EiD8&I*CNC4JVI#tm7_5v)-j&P__}-6{X3q; zSsu^wca5j8>mQO0&$4g-ldbrcMf(S2%V#U#1e88v+{C>|K980-Z;Nk4Nf;9<9QPav z{t@NZ4gScuA}Z@bFi}1*v{yfv*g0qKNwPgP)IX|sqz>pd?gf9`=ihV_hx9Hao-MFCobSi4%M66pP*g^JEw*>55+qLzzqpRf=(D ze-%uZc^8UGXAmahKL@av#Vn0LIZOQJ+6a`=0#w36EYXZZTnRVPv%oB?hNKyfK+v42 z0k3(r8aneABG3r<_&B!Y?bLv^=jP2CsLX$>ffgz_W+Do0KNQEjAB8COKSp7_(`s!j voiV4Pu(;YSE&XTmOC_}z{e=QI0)Lrr0<~bgdA=7|H7_*5SDfdw@ELyxr}F0X delta 1734 zcmeHHT}YEr7~bpm?R?w!vu|_iH>XQc=hU?yS+lEtj6_XIBMU=tO`T%dX4|ABONU7m zMCO6cMHgj3Atb0HcA4IE8x3y?q%Q2L1g#qjj5g=zM53$ms=IT}`=0lC-gBP!8JR~T z^JqMjJHf9AoqP)$=k=;~6sO`Sl;MI!Se(6I2iTY4v5)3!7|Cjdu|U|{(dTOkdi|k3 zZ`fDk5BG)#cWp&-p&U#T)InUW%)){?n>hAE2k}<`!nH`m(@KV1bASdfQ8g%40nZ>4 zJGPH!q=p8#?TTHuK>)U5WW^4LPZZ(FO9$w%A63i288l=XRdbBwcEgx^ zlj+$&r?+FE&l?NrKze(J9pvnGkMdT{7edd&h8C#Yi?A+;r?hB$0B+!FDcJPOjq)lAH?AX&b&S7;qEM8d6W~%TFuBRq>PfUR)5TqdM(F z(Uz&Ctm<9=E76o&ohFxj*sWju(3GRq09CBs!DX(Q?vK)|8wFALNIQ#BT%n1J)55aw z2i3g*T3n}pl7%v8+Z*kP>y+ZZ_WqsrV#E9378q+3f=5trUe#Mwka>*0BZKmlvX_2G z*Cga-rZXctiIM8v5UK3-cloZ?w|ej+Ww!B5$QP{d`kmw+m?0leDLFD}24izdhDC*C zMX4J_dN28QhjIy+A#ZDXi7BzpN+YDNk=JIJ%V^gV z!2%vKTMBvPmIZvql1xTAXNAZqxtHxZ!qq5SlR&HQ+CC!P7O-sE;}XS?SqtdNS}7P~ zUo7ARaZC_X)~MT@dUC@81+f$5a9s8za<2j!WS>czBxi*RnR%5JjtObzR{}x2#v1lw ku!jDIshb`+fqqUOg~F%wsy0TShm67)8iya^Gbd<&0aE59n*aa+ diff --git a/Project/EntityFramework/API/Db.in_english_please.db-shm b/Project/EntityFramework/API/Db.in_english_please.db-shm new file mode 100644 index 0000000000000000000000000000000000000000..a20fab6e321c2115a9100da92db8567ebcfe23f1 GIT binary patch literal 32768 zcmeI*F=_%q6b9gD5@S>ZEdr}okbtd~m8FG^2e1IKGc3r{;b>>`p(6E5FaJ zepBvyuHOXhbt! qZle`l5U5$;A)cdM^O=q#K!5-N0t5&UAV8pAfyZb?`Nw&=B=7@=a3WCv literal 0 HcmV?d00001 diff --git a/Project/EntityFramework/API/Db.in_english_please.db-wal b/Project/EntityFramework/API/Db.in_english_please.db-wal new file mode 100644 index 0000000000000000000000000000000000000000..1ea699cc86c5ee645a826e7b717b977d0406c5cf GIT binary patch literal 41232 zcmeI5Pi)&%9LM9dO`5b>SI{t{7cUc1sJTa#sL+-{<#xFRxFHJ^o5;Co=Neb0e00JNY0w4eaAOHd&00JNY0wB;{1bR9L5}tj5BgDHW zoPB|l*YE!Q=gOOJSo;DGBYh9s%XfGK0w4eaAOHd&00JNY0w4eaAOHd&U=ir(NF>NR zf&A|63v39B1HZ4m`1Hcre9cs)7c_lCF{P8_%LdVCLJ--FagDIs;W_hL_?ceMM%_;BZ`*tgMpQ8lWzQU>||l)&=g zn7BDBL~8Xl^_sD{PBN~dG)#?MSIW9lH`WzXmFs5B+&ZtVDl3h3Mc=ZnE2Awc^zUpP zii^jN3A+=fva+u3RX5ysebXg5Tb8AAb}BDRX;+YzGO46Qj&yDRw46!~?k0QV;_R$&vxl)iqic;T{y0(xt+E#4 z6d$D)wcXIMio9PSH?%z@;p4K|IH?zzG2zO7t)aMRt8hz&E<78PsZg`vw5Z!*3lLf4((j&iHk!+ z!mh}2-DjEavX{?gpVZCWphWdgJNp`YlPz%WDJUCi$i$P|P^w|FbB3x185EooKC>#c zwZYE&Lv3s3W6K(ZXCj$iZd8+TQ51!nBMdofz)n3pUPsdb=5o79OO*49VO%9sc?eE< zL#eHY$eKif_TEHXsI6XZBCdI3NIs|R_*m0UlK`em+Pd0IE?+ZsrCg)Q^DpK_GFLH* z&Wywc(Eivv#eDEtX_N6BoO4!x)D5HJIKxjWb}8Q(YtS^)cAo5xi^q=(H~M{p+i=s| zNbp(bk+=goAXmc2Grx{-!kAa;)rJ}#f8Tn*V@AblYS^!q3Z9QgInT&$N-5Rp^b!1l z|4bq#=8lK0<-DehdM=XNkHy(Q-m%sREFSFC%_DUJb%23vH)%PL19*}d#_WoV0|UbL zBn!LEzlh|}dFK!HUK@{jq}P#HOw101QM4OXM(sE8`OX;q;8|ie+6!ny z-E64!Rn>Rd#o6o=W~jx(q~+lDg^sv*^r-M^g6Xsdqjm1&G+1*A9j6Bfi8Ho6P6w}% z3yqD?nI^rZDtfroP*+Wj$hp-uLA$*u#KrM(VW-GEt5oEfxms0M%$im=o+V3BP2UPE zjPia5)^RcH>7?@=XM;ZlLKJz}IOBd^*VY=V=6UilN{scXC9dV7F>!f3ENcS$sf-2| z)4%P>@kkFjarYOvH74Bu>KE;6dVc{b!Tkj&2pk{)0w4eaAOHd&00JNY0w4eaAkbC> zdOhDG;O;M=kA1nB`TqV7^m_!@7ig=P!x<0&0T2KI5C8!X009sH0T2KI5O4^1_XW87 z3w-hO`)_^l)9qV(`vSPXfWr*0AOHd&00JNY0w4eaAOHd&00JP;ZUpFk0l4oGy!ZUt z#BJlbNj#^p-9in2KmY_l00ck)1V8`;KmY_l00cn5BGBwPg@4`2{P@YoW1r$Vg~%2V z009sH0T2KI5C8!X009sH0T5_U0?nRNxbp7jXD_DazQc10+cWm?3Isp^1V8`;KmY_l S00ck)1V8`;90K$?h5rC;+MQVd literal 0 HcmV?d00001 diff --git a/Project/EntityFramework/DTOToEntity/GroupService.cs b/Project/EntityFramework/DTOToEntity/GroupService.cs index 45c1cd1..a27893d 100644 --- a/Project/EntityFramework/DTOToEntity/GroupService.cs +++ b/Project/EntityFramework/DTOToEntity/GroupService.cs @@ -14,16 +14,16 @@ namespace DTOToEntity public class GroupService : IGroupService { - private readonly StubbedContext context = new StubbedContext(); + private readonly UnitOfWork context = new UnitOfWork(); public GroupService() { } - public GroupService(StubbedContext context) + public GroupService(StubbedContext _context) { - this.context = context; + context = new UnitOfWork(_context); } public async Task Add(GroupDTO group) { @@ -31,21 +31,21 @@ namespace DTOToEntity { throw new ArgumentNullException(); } - var groupEntity = group.ToEntity(); - var res = context.Groups.Add(groupEntity); - await context.SaveChangesAsync(); + GroupEntity groupEntity = group.ToEntity(); + context.GroupRepository.Insert(groupEntity); + await context.SaveChangesAsync(); - return res.Entity.ToDTO(); ; + return groupEntity.ToDTO(); ; } public async Task AddUserToGroup(long idUser, long idGroup) { - var group = context.Groups.Find(idGroup); + var group = context.GroupRepository.GetById(idGroup); if (group == null) { throw new Exception("Group not found"); } - var user = context.Users.Find(idUser); + var user = context.UserRepository.GetById(idUser); if (user == null) { throw new Exception("User not found"); @@ -58,17 +58,18 @@ namespace DTOToEntity public async Task AddVocabularyListToGroup(long vocabId, long groupId) { - var group = context.Groups.Find(groupId); + var group = context.GroupRepository.GetById(groupId); if (group == null) { throw new Exception("Group not found"); } - var vocab = context.VocabularyLists.Find(vocabId); + var vocab = context.VocabularyListRepository.GetById(vocabId); if (vocab == null) { throw new Exception("VocabularyList not found"); } group.GroupVocabularyList.Add(vocab); + await context.SaveChangesAsync(); return vocab.ToDTO(); @@ -76,10 +77,10 @@ namespace DTOToEntity public async Task Delete(object id) { - var group = await context.Groups.FindAsync((long)id); + var group = context.GroupRepository.GetById((long)id); if (group != null) - { - context.Groups.Remove(group); + { + context.GroupRepository.Delete(group); await context.SaveChangesAsync(); }else { @@ -90,7 +91,7 @@ namespace DTOToEntity public async Task GetById(object id) { - var group = await context.Groups.FindAsync((long)id); + var group = context.GroupRepository.GetById((long) id); if (group == null) { throw new Exception("Group not found"); @@ -100,26 +101,26 @@ namespace DTOToEntity public async Task> GetByNum(int index, int count, int num) { - var groups = context.Groups.Where(g => g.Num == num).Skip(index * count).Take(count); - return new PageResponse(groups.ToList().Select(g => g.ToDTO()), context.Groups.Count()); + var groups = context.GroupRepository.GetItems(filter: g => g.Num == num, index, count); + return new PageResponse(groups.ToList().Select(g => g.ToDTO()), context.GroupRepository.GetItems(0, 1000000000).Count()); } public async Task> GetBySector(int index, int count, string sector) { - var groups = context.Groups.Where(g => g.sector == sector).Skip(index * count).Take(count); - return new PageResponse(groups.ToList().Select(g => g.ToDTO()), context.Groups.Count()); + var groups = context.GroupRepository.GetItems(filter: g => g.sector == sector, index, count); + return new PageResponse(groups.ToList().Select(g => g.ToDTO()), context.GroupRepository.GetItems(0, 100000000).Count()); } public async Task> GetByYear(int index, int count, int year) { - var groups = context.Groups.Where(g => g.year == year).Skip(index * count).Take(count); - return new PageResponse(groups.ToList().Select(g => g.ToDTO()), context.Groups.Count()); + var groups = context.GroupRepository.GetItems(filter: g => g.year == year, index, count); + return new PageResponse(groups.ToList().Select(g => g.ToDTO()), context.GroupRepository.GetItems(0,100000000).Count()); } public async Task> Gets(int index, int count) { - IEnumerable groups = await context.Groups.Skip(index * count).Take(count).ToListAsync(); - return new PageResponse(groups.ToList().Select(g => g.ToDTO()), context.Groups.Count()); + IEnumerable groups = context.GroupRepository.GetItems(index,count); + return new PageResponse(groups.ToList().Select(g => g.ToDTO()), context.GroupRepository.GetItems(0, 1000000000).Count()); } public async Task Update(GroupDTO group) @@ -128,7 +129,7 @@ namespace DTOToEntity { throw new ArgumentNullException(); } - var existingGroup = await context.Groups.FindAsync(group.Id); + var existingGroup = context.GroupRepository.GetById(group.Id); if (existingGroup == null) { throw new Exception("Group not found"); diff --git a/Project/EntityFramework/DTOToEntity/LangueService.cs b/Project/EntityFramework/DTOToEntity/LangueService.cs index 75e41cb..280f015 100644 --- a/Project/EntityFramework/DTOToEntity/LangueService.cs +++ b/Project/EntityFramework/DTOToEntity/LangueService.cs @@ -1,4 +1,5 @@ -using DTO; +using DbContextLib; +using DTO; using Entities; using Microsoft.EntityFrameworkCore; using StubbedContextLib; @@ -12,29 +13,29 @@ namespace DTOToEntity { public class LangueService : IService { - private readonly StubbedContext _context = new StubbedContext(); + private readonly UnitOfWork _context = new UnitOfWork(); public LangueService() { } public LangueService(StubbedContext context) { - this._context = context; + this._context = new UnitOfWork(context); } public async Task Add(LangueDTO langue) { var langueEntity = langue.ToEntity(); - var res = _context.Langues.Add(langueEntity); + _context.LangueRepository.Insert(langueEntity); await _context.SaveChangesAsync(); - return res.Entity.ToDTO(); + return langue; } public async Task Delete(object id) { - var langue = await _context.Langues.FindAsync(id); + var langue = _context.LangueRepository.GetById(id); if (langue != null) { - _context.Langues.Remove(langue); - await _context.SaveChangesAsync(); + _context.LangueRepository.Delete(langue); + await _context.SaveChangesAsync(); } else { throw new Exception("Langue not found"); @@ -44,7 +45,7 @@ namespace DTOToEntity public async Task GetById(object id) { - var langue = await _context.Langues.FindAsync(id); + var langue = _context.LangueRepository.GetById(id); if (langue == null) { throw new Exception("Langue not found"); @@ -55,13 +56,13 @@ namespace DTOToEntity public async Task> Gets(int index,int count) { - IEnumerable langues = await _context.Langues.Skip(index * count).Take(count).ToListAsync(); - return new PageResponse(langues.ToList().Select(l => l.ToDTO()), _context.Langues.Count()); + IEnumerable langues = _context.LangueRepository.GetItems(index, count); + return new PageResponse(langues.ToList().Select(l => l.ToDTO()), _context.LangueRepository.GetItems(0, 1000000000).Count()); } public async Task Update(LangueDTO langue) { - LangueEntity? langueToUpdate = await _context.Langues.FindAsync(langue.name); + LangueEntity? langueToUpdate = _context.LangueRepository.GetById(langue.name); if (langueToUpdate == null) { throw new Exception("Langue not found"); diff --git a/Project/EntityFramework/DTOToEntity/RoleService.cs b/Project/EntityFramework/DTOToEntity/RoleService.cs index b84f50a..a319dc7 100644 --- a/Project/EntityFramework/DTOToEntity/RoleService.cs +++ b/Project/EntityFramework/DTOToEntity/RoleService.cs @@ -1,4 +1,5 @@ -using DTO; +using DbContextLib; +using DTO; using Entities; using Microsoft.EntityFrameworkCore; using StubbedContextLib; @@ -12,40 +13,41 @@ namespace DTOToEntity { public class RoleService : IService { - private readonly StubbedContext _context = new StubbedContext(); + private readonly UnitOfWork _context = new UnitOfWork(); public RoleService() { } public RoleService(StubbedContext context) + { + _context = new UnitOfWork(context); + } + + public RoleService(UnitOfWork context) { _context = context; } public async Task Add(RoleDTO role) { var roleEntity = role.ToEntity(); - if(roleEntity == null) - { - throw new ArgumentNullException(); - } - var res = _context.Roles.Add(roleEntity); + _context.RoleRepository.Insert(roleEntity); await _context.SaveChangesAsync(); - return res.Entity.ToDTO(); + return role; } public async Task Delete(object id) { - RoleEntity? role = await _context.Roles.FirstOrDefaultAsync(r => r.Id == (int)id); + RoleEntity role = _context.RoleRepository.GetById((long)id); if (role == null) { throw new Exception("Role not found"); } - var res = _context.Roles.Remove(role); + _context.RoleRepository.Delete((long)id); await _context.SaveChangesAsync(); - return res.Entity.ToDTO(); + return role.ToDTO(); } public async Task GetById(object id) { - RoleEntity? role = await _context.Roles.FirstOrDefaultAsync(r => r.Id == (int)id); + RoleEntity? role = _context.RoleRepository.GetById((long)id); if (role == null) { throw new Exception("Role not found"); @@ -55,8 +57,8 @@ namespace DTOToEntity public async Task> Gets(int index, int count) { - IEnumerable roles = await _context.Roles.Skip(index * count).Take(count).ToListAsync(); - return new PageResponse(roles.ToList().Select(r => r.ToDTO()), _context.Roles.Count()); + IEnumerable roles = _context.RoleRepository.GetItems(index, count); + return new PageResponse(roles.ToList().Select(r => r.ToDTO()), _context.RoleRepository.GetItems(0,1000000000).Count()); } public async Task Update(RoleDTO role) @@ -65,12 +67,13 @@ namespace DTOToEntity { throw new ArgumentNullException(); } - var roleEntity = await _context.Roles.FindAsync(role.Id); + var roleEntity = _context.RoleRepository.GetById(role.Id); if (roleEntity != null) { throw new Exception("role not found"); } roleEntity.Name = role.Name; + _context.RoleRepository.Update(roleEntity); await _context.SaveChangesAsync(); return roleEntity.ToDTO(); } diff --git a/Project/EntityFramework/DTOToEntity/TranslateService.cs b/Project/EntityFramework/DTOToEntity/TranslateService.cs index 7739b82..4bdca81 100644 --- a/Project/EntityFramework/DTOToEntity/TranslateService.cs +++ b/Project/EntityFramework/DTOToEntity/TranslateService.cs @@ -1,4 +1,5 @@ -using DTO; +using DbContextLib; +using DTO; using Microsoft.EntityFrameworkCore; using StubbedContextLib; using System; @@ -11,18 +12,18 @@ namespace DTOToEntity { public class TranslateService : ITranslateService { - private readonly StubbedContext _context = new StubbedContext(); + private readonly UnitOfWork _context = new UnitOfWork(); public TranslateService() { } public TranslateService(StubbedContext context) { - _context = context; + _context = new UnitOfWork(context); } public async Task Add(TranslateDTO translate) { var translateEntity = translate.ToEntity(); - _context.Translates.Add(translateEntity); + _context.TranslateRepository.Insert(translateEntity); await _context.SaveChangesAsync(); return translateEntity.ToDTO(); @@ -30,12 +31,12 @@ namespace DTOToEntity public async Task AddVocabToTranslate(string vocabId, long translateId) { - var vocab = _context.Vocabularys.Find(vocabId); + var vocab = _context.VocabularyRepository.GetById(vocabId); if (vocab == null) { throw new Exception("Vocabulary not found"); } - var translate = _context.Translates.Find(translateId); + var translate = _context.TranslateRepository.GetById(translateId); if (translate == null) { throw new Exception("Translate not found"); @@ -47,10 +48,10 @@ namespace DTOToEntity public async Task Delete(object id) { - var translate = await _context.Translates.FirstOrDefaultAsync(t => t.Id == (int)id); + var translate = _context.TranslateRepository.GetById((long)id); if (translate != null) { - _context.Translates.Remove(translate); + _context.TranslateRepository.Delete(translate); await _context.SaveChangesAsync(); } else @@ -62,7 +63,7 @@ namespace DTOToEntity public async Task GetById(object id) { - var translate = await _context.Translates.FirstOrDefaultAsync(t => t.Id == (int)id); + var translate = _context.TranslateRepository.GetById((long)id); if (translate == null) { throw new Exception("Translate not found"); @@ -72,24 +73,24 @@ namespace DTOToEntity public async Task> Gets(int index, int count) { - var translates = await _context.Translates.Skip(index * count).Take(count).ToListAsync(); + var translates = _context.TranslateRepository.GetItems(index, count); if(translates == null) { throw new Exception("No translates found"); } - return new PageResponse( translates.Select(t => t.ToDTO()), _context.Translates.Count()); + return new PageResponse( translates.Select(t => t.ToDTO()), _context.TranslateRepository.GetItems(0, 100000000).Count()); } public async Task Update(TranslateDTO translate) { - var translateEntity = await _context.Translates.FirstOrDefaultAsync(t => t.Id == translate.Id); + var translateEntity = _context.TranslateRepository.GetById(translate.Id); if (translateEntity == null) { throw new Exception("Translate not found"); } translateEntity.WordsId = translate.WordsId; translateEntity.VocabularyListVocId = translate.VocabularyListVocId; - _context.Translates.Update(translateEntity); + _context.TranslateRepository.Update(translateEntity); await _context.SaveChangesAsync(); return translateEntity.ToDTO(); } diff --git a/Project/EntityFramework/DTOToEntity/UserService.cs b/Project/EntityFramework/DTOToEntity/UserService.cs index 676430d..47febdc 100644 --- a/Project/EntityFramework/DTOToEntity/UserService.cs +++ b/Project/EntityFramework/DTOToEntity/UserService.cs @@ -1,9 +1,11 @@ -using DTO; +using DbContextLib; +using DTO; using Entities; using Microsoft.EntityFrameworkCore; using StubbedContextLib; using System; using System.Collections.Generic; +using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; @@ -12,12 +14,12 @@ namespace DTOToEntity { public class UserService : IUserService { - private StubbedContext _context = new StubbedContext(); + private UnitOfWork _context = new UnitOfWork(); public UserService() { } public UserService(StubbedContext context) { - _context = context; + _context = new UnitOfWork(context); } public async Task Add(UserDTO user) { @@ -26,32 +28,32 @@ namespace DTOToEntity { throw new Exception("User Entity is null"); } - var result = _context.Users.Add(userEntity); + _context.UserRepository.Insert(userEntity); await _context.SaveChangesAsync(); - return result.Entity.ToDTO(); + return user; } public async Task Delete(object id) { - UserEntity? user = await _context.Users.FirstOrDefaultAsync(u => u.Id == (long)id); + UserEntity? user = _context.UserRepository.GetById((long)id); if(user == null) { throw new Exception("User not found"); } - _context.Users.Remove(user); + _context.UserRepository.Delete((long)id); await _context.SaveChangesAsync(); return user.ToDTO(); } public async Task> GetByGroup(int index, int count, long group) { - var users = _context.Users.Where(u => u.GroupId == group).Skip(index * count).Take(count); - return new PageResponse(users.Select(u => u.ToDTO()), _context.Users.Count()); + var users = _context.UserRepository.GetItems(index,count).Where(u => u.GroupId == group); + return new PageResponse(users.Select(u => u.ToDTO()), _context.UserRepository.GetItems(0,1000000000).Count()); } public async Task GetById(object id) { - var user = await _context.Users.FirstOrDefaultAsync(u => u.Id == (long)id); + var user = _context.UserRepository.GetById((long)id); if(user == null) { throw new Exception("User not found"); @@ -62,14 +64,16 @@ namespace DTOToEntity public async Task> GetByRole(int index, int count, string role) { - var users = _context.Users.Where(u => u.Role.Name == role).Skip(index * count).Take(count); - return new PageResponse(users.Select(u => u.ToDTO()), _context.Users.Count()); + var users = _context.UserRepository.GetItems(filter: u => u.Role != null && u.Role.Name == role, + index: index, + count: count); + return new PageResponse(users.Select(u => u.ToDTO()), _context.UserRepository.GetItems(0, 1000000000).Count()); } public async Task> Gets(int index, int count) { - IEnumerable users = await _context.Users.Skip(index * count).Take(count).ToListAsync(); - return new PageResponse( users.Select(u => u.ToDTO()),_context.Users.Count()); + IEnumerable users = _context.UserRepository.GetItems(index, count) ; + return new PageResponse( users.Select(u => u.ToDTO()),_context.UserRepository.GetItems(0, 1000000000).Count()); } public async Task Update(UserDTO user) @@ -78,7 +82,7 @@ namespace DTOToEntity { throw new Exception("User is null"); } - var existingUser = await _context.Users.FirstOrDefaultAsync(u => u.Id == user.Id); + var existingUser = _context.UserRepository.GetById(user.Id); if(existingUser == null) { throw new Exception("User not found"); diff --git a/Project/EntityFramework/DTOToEntity/VocabularyListService.cs b/Project/EntityFramework/DTOToEntity/VocabularyListService.cs index f9999b1..0f0bde6 100644 --- a/Project/EntityFramework/DTOToEntity/VocabularyListService.cs +++ b/Project/EntityFramework/DTOToEntity/VocabularyListService.cs @@ -1,4 +1,5 @@ -using DTO; +using DbContextLib; +using DTO; using Microsoft.EntityFrameworkCore; using StubbedContextLib; using System; @@ -11,7 +12,7 @@ namespace DTOToEntity { public class VocabularyListService : IVocabularyListService { - private StubbedContext _context = new StubbedContext(); + private UnitOfWork _context = new UnitOfWork(); public VocabularyListService() { @@ -19,24 +20,24 @@ namespace DTOToEntity public VocabularyListService(StubbedContext context) { - _context = context; + _context = new UnitOfWork(context); } public async Task Add(VocabularyListDTO group) { var groupEntity = group.ToEntity(); - _context.VocabularyLists.Add(groupEntity); + _context.VocabularyListRepository.Insert(groupEntity); await _context.SaveChangesAsync(); return groupEntity.ToDTO(); } public async Task AddGroupToVocabularyList(long groupId, long vocabId) { - var group = _context.Groups.Find(groupId); + var group = _context.GroupRepository.GetById(groupId); if (group == null) { throw new Exception("Group not found"); } - var vocab = _context.VocabularyLists.Find(vocabId); + var vocab = _context.VocabularyListRepository.GetById(vocabId); if (vocab == null) { throw new Exception("Vocabulary List not found"); @@ -49,10 +50,10 @@ namespace DTOToEntity public async Task Delete(object id) { - var group = await _context.VocabularyLists.FindAsync(id); + var group = _context.VocabularyListRepository.GetById((long)id); if (group != null) { - _context.VocabularyLists.Remove(group); + _context.VocabularyListRepository.Delete(group); await _context.SaveChangesAsync(); } else @@ -64,7 +65,7 @@ namespace DTOToEntity public async Task GetById(object id) { - var group = await _context.VocabularyLists.FindAsync(id); + var group = _context.VocabularyListRepository.GetById((long)id); if (group == null) { throw new Exception("Group not found"); @@ -74,15 +75,15 @@ namespace DTOToEntity public async Task> GetByUser(int index, int count, int user) { - var groups = _context.VocabularyLists.Where(g => g.UserId == user).Skip(index * count).Take(count); - return new PageResponse(groups.Select(g => g.ToDTO()), _context.VocabularyLists.Count()); + var groups = _context.VocabularyListRepository.GetItems(filter: u => u.Id == user, index, count); + return new PageResponse(groups.Select(g => g.ToDTO()), _context.VocabularyListRepository.GetItems(0,1000000000).Count()); } public async Task> Gets(int index, int count) { - var groups = await _context.VocabularyLists.Skip(index * count).Take(count).ToListAsync(); - return new PageResponse(groups.Select(g => g.ToDTO()), _context.VocabularyLists.Count()); + var groups = _context.VocabularyListRepository.GetItems(index, count); + return new PageResponse(groups.Select(g => g.ToDTO()), _context.VocabularyListRepository.GetItems(0, 1000000000).Count()); } public async Task Update(VocabularyListDTO group) @@ -92,9 +93,9 @@ namespace DTOToEntity { throw new Exception("Group Entity is null"); } - var res = _context.VocabularyLists.Update(groupEntity); + _context.VocabularyListRepository.Update(groupEntity); await _context.SaveChangesAsync(); - return res.Entity.ToDTO(); + return group; } } } diff --git a/Project/EntityFramework/DTOToEntity/VocabularyService.cs b/Project/EntityFramework/DTOToEntity/VocabularyService.cs index 7f1ac16..54f766f 100644 --- a/Project/EntityFramework/DTOToEntity/VocabularyService.cs +++ b/Project/EntityFramework/DTOToEntity/VocabularyService.cs @@ -1,4 +1,5 @@ -using DTO; +using DbContextLib; +using DTO; using Entities; using Microsoft.EntityFrameworkCore; using StubbedContextLib; @@ -12,13 +13,13 @@ namespace DTOToEntity { public class VocabularyService : IVocabularyService { - private readonly StubbedContext _context = new StubbedContext(); + private readonly UnitOfWork _context = new UnitOfWork(); public VocabularyService() { } public VocabularyService(StubbedContext context) { - _context = context; + _context = new UnitOfWork(context); } public async Task Add(VocabularyDTO vocabulary) { @@ -27,19 +28,19 @@ namespace DTOToEntity { throw new ArgumentNullException(); } - await _context.Vocabularys.AddAsync(vocabularyEntity); + _context.VocabularyRepository.Insert(vocabularyEntity); await _context.SaveChangesAsync(); return vocabularyEntity.ToDTO(); } public async Task AddTranslationToVocabulary(string vocabId, long translateId) { - var vocabulary = _context.Vocabularys.Find(vocabId); + var vocabulary = _context.VocabularyRepository.GetById(vocabId); if(vocabulary == null) { throw new Exception("Vocabulary not found"); } - var translate = _context.Translates.Find(translateId); + var translate = _context.TranslateRepository.GetById(translateId); if(translate == null) { throw new Exception("Translate not found"); @@ -51,19 +52,19 @@ namespace DTOToEntity public async Task Delete(object id) { - var vocabulary = await _context.Vocabularys.FirstOrDefaultAsync(v => v.word == (string)id); + var vocabulary = _context.VocabularyRepository.GetById((string)id); if(vocabulary == null) { throw new Exception("Vocabulary not found"); } - _context.Vocabularys.Remove(vocabulary); + _context.VocabularyRepository.Delete(vocabulary); await _context.SaveChangesAsync(); return vocabulary.ToDTO(); } public async Task GetById(object id) { - var vocabulary = await _context.Vocabularys.FirstOrDefaultAsync(v => v.word == (string)id); + var vocabulary = _context.VocabularyRepository.GetById((string)id); if(vocabulary == null) { throw new Exception("Vocabulary not found"); @@ -73,15 +74,15 @@ namespace DTOToEntity public async Task> GetByLangue(int index, int count, string langue) { - var vocabularies = _context.Vocabularys.Where(v => v.LangueName == langue).Skip(index * count).Take(count); - return new PageResponse(vocabularies.ToList().Select(v => v.ToDTO()), _context.Vocabularys.Count()); + var vocabularies = _context.VocabularyRepository.GetItems(filter: v => v.LangueName == langue, index, count); + return new PageResponse(vocabularies.ToList().Select(v => v.ToDTO()), _context.VocabularyRepository.GetItems(0,100000000).Count()); } public async Task> Gets(int index, int count) { - var vocabulary = await _context.Vocabularys.Skip(index * count).Take(count).ToListAsync(); - return new PageResponse(vocabulary.Select(v => v.ToDTO()), _context.Vocabularys.Count()); + var vocabulary = _context.VocabularyRepository.GetItems(index, count); + return new PageResponse(vocabulary.Select(v => v.ToDTO()), _context.VocabularyRepository.GetItems(0, 100000000).Count()); } public async Task Update(VocabularyDTO vocabulary) @@ -91,7 +92,7 @@ namespace DTOToEntity { throw new Exception("vocabulary not valid"); } - var VocabToUpdate = _context.Vocabularys.FirstOrDefault(v => v.word == (string)vocabularyEntity.word); + var VocabToUpdate = _context.VocabularyRepository.GetById(vocabulary.word); if(VocabToUpdate == null) { throw new Exception("vocabulary not found"); diff --git a/Project/EntityFramework/DbContext/SAEContext.cs b/Project/EntityFramework/DbContext/SAEContext.cs index 4affeff..5909483 100644 --- a/Project/EntityFramework/DbContext/SAEContext.cs +++ b/Project/EntityFramework/DbContext/SAEContext.cs @@ -15,11 +15,6 @@ namespace DbContextLib public DbSet Vocabularys { get; set; } public DbSet VocabularyLists { get; set; } - public DbSet GroupVocabularyList { get; set; } - public DbSet VocsGroups { get; set; } - public DbSet Voctranslations { get; set; } - public DbSet TransVoc { get; set; } - //permet de créer une base de donnée (fichier .db) ici en Sqlite avec le nom Db.Books.db diff --git a/Project/EntityFramework/StubbedContext/GenericRepository.cs b/Project/EntityFramework/StubbedContext/GenericRepository.cs new file mode 100644 index 0000000..d39ae65 --- /dev/null +++ b/Project/EntityFramework/StubbedContext/GenericRepository.cs @@ -0,0 +1,169 @@ +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Text; +using System.Threading.Tasks; + +namespace DbContextLib +{ + public class GenericRepository where TEntity : class + { + private DbContext Context { get; set; } + private DbSet Set { get; set; } + + public GenericRepository(DbContext context) + { + Context = context; + Set = Context.Set(); + } + + public virtual TEntity? GetById(object id) + { + return Context.Set().Find(id); + } + + public virtual IEnumerable GetItems(Expression>? filter = null, + int index = 0, int count = 10, + params string[] includeProperties) + => GetItems(filter, null, index, count, includeProperties); + + public virtual IEnumerable GetItems(Func, IOrderedQueryable>? orderBy = null, + int index = 0, int count = 10, + params string[] includeProperties) + => GetItems(null, orderBy, index, count, includeProperties); + + public virtual IEnumerable GetItems(int index = 0, int count = 10, + params string[] includeProperties) + => GetItems(null, null, index, count, includeProperties); + + public virtual IEnumerable GetItems(Expression>? filter = null, + Func, IOrderedQueryable>? orderBy = null, + int index = 0, int count = 10, + params string[] includeProperties) + { + IQueryable query = Set; + if (filter != null) + { + query = query.Where(filter); + } + foreach (string includeProperty in includeProperties) + { + query = query.Include(includeProperty); + } + if (orderBy != null) + { + query = orderBy(query); + } + return query.Skip(index * count) + .Take(count) + .ToList(); + } + + public virtual void Insert(TEntity entity) + { + var primaryKeyProperty = Context.Model.FindEntityType(typeof(TEntity)).FindPrimaryKey().Properties.FirstOrDefault(); + if (primaryKeyProperty != null) + { + var parameter = Expression.Parameter(typeof(TEntity), "x"); + var property = Expression.Property(parameter, primaryKeyProperty.Name); + var idValue = Expression.Constant(primaryKeyProperty.GetGetter().GetClrValue(entity)); + var equal = Expression.Equal(property, idValue); + var lambda = Expression.Lambda>(equal, parameter); + + var existingEntity = Set.Local.FirstOrDefault(lambda.Compile()); + + if (existingEntity != null) + { + Set.Entry(existingEntity).Property("Count").CurrentValue = (int)Set.Entry(existingEntity).Property("Count").CurrentValue + 1; + } + else + { + Set.Add(entity); + } + } + else + { + throw new InvalidOperationException("Cannot find primary key property for entity type."); + } + } + + public virtual void Insert(params TEntity[] entities) + { + foreach (var entity in entities) + { + Insert(entity); + } + } + + public virtual void Delete(object id) + { + TEntity? entity = Set.Find(id); + if (entity == null) return; + Delete(entity); + } + + public virtual void Delete(TEntity entity) + { + var primaryKeyProperty = Context.Model.FindEntityType(typeof(TEntity)).FindPrimaryKey().Properties.FirstOrDefault(); + if (primaryKeyProperty != null) + { + var parameter = Expression.Parameter(typeof(TEntity), "x"); + var property = Expression.Property(parameter, primaryKeyProperty.Name); + var idValue = Expression.Constant(primaryKeyProperty.GetGetter().GetClrValue(entity)); + var equal = Expression.Equal(property, idValue); + var lambda = Expression.Lambda>(equal, parameter); + + var existingEntity = Set.Local.FirstOrDefault(lambda.Compile()); + + if (existingEntity == null) + { + if (Context.Entry(entity).State == EntityState.Detached) + { + Set.Attach(entity); + } + Set.Remove(entity); + } + else + { + Set.Remove(existingEntity); + } + } + else + { + throw new InvalidOperationException("Cannot find primary key property for entity type."); + } + } + + public virtual void Update(TEntity entity) + { + var primaryKeyProperty = Context.Model.FindEntityType(typeof(TEntity)).FindPrimaryKey().Properties.FirstOrDefault(); + if (primaryKeyProperty != null) + { + var parameter = Expression.Parameter(typeof(TEntity), "x"); + var property = Expression.Property(parameter, primaryKeyProperty.Name); + var idValue = Expression.Constant(primaryKeyProperty.GetGetter().GetClrValue(entity)); + var equal = Expression.Equal(property, idValue); + var lambda = Expression.Lambda>(equal, parameter); + + var existingEntity = Set.Local.FirstOrDefault(lambda.Compile()); + + if (existingEntity != null) + { + Context.Entry(existingEntity).CurrentValues.SetValues(entity); + } + else + { + Set.Attach(entity); + Context.Entry(entity).State = EntityState.Modified; + } + } + else + { + throw new InvalidOperationException("Cannot find primary key property for entity type."); + } + } + + } +} diff --git a/Project/EntityFramework/StubbedContext/Migrations/20240316154336_newMigs.Designer.cs b/Project/EntityFramework/StubbedContext/Migrations/20240331212614_newMigs.Designer.cs similarity index 98% rename from Project/EntityFramework/StubbedContext/Migrations/20240316154336_newMigs.Designer.cs rename to Project/EntityFramework/StubbedContext/Migrations/20240331212614_newMigs.Designer.cs index 0cf189d..aa8caf1 100644 --- a/Project/EntityFramework/StubbedContext/Migrations/20240316154336_newMigs.Designer.cs +++ b/Project/EntityFramework/StubbedContext/Migrations/20240331212614_newMigs.Designer.cs @@ -10,7 +10,7 @@ using StubbedContextLib; namespace StubbedContextLib.Migrations { [DbContext(typeof(StubbedContext))] - [Migration("20240316154336_newMigs")] + [Migration("20240331212614_newMigs")] partial class newMigs { /// @@ -37,7 +37,7 @@ namespace StubbedContextLib.Migrations b.HasKey("Id"); - b.ToTable("GroupEntity"); + b.ToTable("Groups"); b.HasData( new @@ -118,7 +118,7 @@ namespace StubbedContextLib.Migrations b.HasIndex("VocabularyListVocId"); - b.ToTable("TranslateEntity"); + b.ToTable("Translates"); b.HasData( new @@ -227,7 +227,7 @@ namespace StubbedContextLib.Migrations b.HasIndex("LangueName"); - b.ToTable("VocabularyEntity"); + b.ToTable("Vocabularys"); b.HasData( new @@ -258,7 +258,7 @@ namespace StubbedContextLib.Migrations b.HasIndex("UserId"); - b.ToTable("VocabularyListEntity"); + b.ToTable("VocabularyLists"); b.HasData( new diff --git a/Project/EntityFramework/StubbedContext/Migrations/20240316154336_newMigs.cs b/Project/EntityFramework/StubbedContext/Migrations/20240331212614_newMigs.cs similarity index 85% rename from Project/EntityFramework/StubbedContext/Migrations/20240316154336_newMigs.cs rename to Project/EntityFramework/StubbedContext/Migrations/20240331212614_newMigs.cs index c81fcd3..6377dc5 100644 --- a/Project/EntityFramework/StubbedContext/Migrations/20240316154336_newMigs.cs +++ b/Project/EntityFramework/StubbedContext/Migrations/20240331212614_newMigs.cs @@ -13,7 +13,7 @@ namespace StubbedContextLib.Migrations protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( - name: "GroupEntity", + name: "Groups", columns: table => new { Id = table.Column(type: "INTEGER", nullable: false) @@ -24,7 +24,7 @@ namespace StubbedContextLib.Migrations }, constraints: table => { - table.PrimaryKey("PK_GroupEntity", x => x.Id); + table.PrimaryKey("PK_Groups", x => x.Id); }); migrationBuilder.CreateTable( @@ -52,7 +52,7 @@ namespace StubbedContextLib.Migrations }); migrationBuilder.CreateTable( - name: "VocabularyEntity", + name: "Vocabularys", columns: table => new { word = table.Column(type: "TEXT", nullable: false), @@ -60,9 +60,9 @@ namespace StubbedContextLib.Migrations }, constraints: table => { - table.PrimaryKey("PK_VocabularyEntity", x => x.word); + table.PrimaryKey("PK_Vocabularys", x => x.word); table.ForeignKey( - name: "FK_VocabularyEntity_Langues_LangueName", + name: "FK_Vocabularys_Langues_LangueName", column: x => x.LangueName, principalTable: "Langues", principalColumn: "name", @@ -89,9 +89,9 @@ namespace StubbedContextLib.Migrations { table.PrimaryKey("PK_Users", x => x.Id); table.ForeignKey( - name: "FK_Users_GroupEntity_GroupId", + name: "FK_Users_Groups_GroupId", column: x => x.GroupId, - principalTable: "GroupEntity", + principalTable: "Groups", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( @@ -103,7 +103,7 @@ namespace StubbedContextLib.Migrations }); migrationBuilder.CreateTable( - name: "VocabularyListEntity", + name: "VocabularyLists", columns: table => new { Id = table.Column(type: "INTEGER", nullable: false) @@ -114,9 +114,9 @@ namespace StubbedContextLib.Migrations }, constraints: table => { - table.PrimaryKey("PK_VocabularyListEntity", x => x.Id); + table.PrimaryKey("PK_VocabularyLists", x => x.Id); table.ForeignKey( - name: "FK_VocabularyListEntity_Users_UserId", + name: "FK_VocabularyLists_Users_UserId", column: x => x.UserId, principalTable: "Users", principalColumn: "Id", @@ -134,21 +134,21 @@ namespace StubbedContextLib.Migrations { table.PrimaryKey("PK_GroupEntityVocabularyListEntity", x => new { x.GroupVocabularyListId, x.VocsGroupsId }); table.ForeignKey( - name: "FK_GroupEntityVocabularyListEntity_GroupEntity_VocsGroupsId", + name: "FK_GroupEntityVocabularyListEntity_Groups_VocsGroupsId", column: x => x.VocsGroupsId, - principalTable: "GroupEntity", + principalTable: "Groups", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( - name: "FK_GroupEntityVocabularyListEntity_VocabularyListEntity_GroupVocabularyListId", + name: "FK_GroupEntityVocabularyListEntity_VocabularyLists_GroupVocabularyListId", column: x => x.GroupVocabularyListId, - principalTable: "VocabularyListEntity", + principalTable: "VocabularyLists", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( - name: "TranslateEntity", + name: "Translates", columns: table => new { Id = table.Column(type: "INTEGER", nullable: false) @@ -158,11 +158,11 @@ namespace StubbedContextLib.Migrations }, constraints: table => { - table.PrimaryKey("PK_TranslateEntity", x => x.Id); + table.PrimaryKey("PK_Translates", x => x.Id); table.ForeignKey( - name: "FK_TranslateEntity_VocabularyListEntity_VocabularyListVocId", + name: "FK_Translates_VocabularyLists_VocabularyListVocId", column: x => x.VocabularyListVocId, - principalTable: "VocabularyListEntity", + principalTable: "VocabularyLists", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); @@ -178,21 +178,21 @@ namespace StubbedContextLib.Migrations { table.PrimaryKey("PK_TranslateEntityVocabularyEntity", x => new { x.TransVocword, x.VoctranslationsId }); table.ForeignKey( - name: "FK_TranslateEntityVocabularyEntity_TranslateEntity_VoctranslationsId", + name: "FK_TranslateEntityVocabularyEntity_Translates_VoctranslationsId", column: x => x.VoctranslationsId, - principalTable: "TranslateEntity", + principalTable: "Translates", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( - name: "FK_TranslateEntityVocabularyEntity_VocabularyEntity_TransVocword", + name: "FK_TranslateEntityVocabularyEntity_Vocabularys_TransVocword", column: x => x.TransVocword, - principalTable: "VocabularyEntity", + principalTable: "Vocabularys", principalColumn: "word", onDelete: ReferentialAction.Cascade); }); migrationBuilder.InsertData( - table: "GroupEntity", + table: "Groups", columns: new[] { "Id", "Num", "sector", "year" }, values: new object[] { 1L, 1, "informatics", 1 }); @@ -226,17 +226,17 @@ namespace StubbedContextLib.Migrations }); migrationBuilder.InsertData( - table: "VocabularyEntity", + table: "Vocabularys", columns: new[] { "word", "LangueName" }, values: new object[] { "Bonjour", "French" }); migrationBuilder.InsertData( - table: "VocabularyListEntity", + table: "VocabularyLists", columns: new[] { "Id", "Image", "Name", "UserId" }, values: new object[] { 1L, "image1", "Liste1", 1L }); migrationBuilder.InsertData( - table: "TranslateEntity", + table: "Translates", columns: new[] { "Id", "VocabularyListVocId", "WordsId" }, values: new object[] { 1L, 1L, "1" }); @@ -245,16 +245,16 @@ namespace StubbedContextLib.Migrations table: "GroupEntityVocabularyListEntity", column: "VocsGroupsId"); - migrationBuilder.CreateIndex( - name: "IX_TranslateEntity_VocabularyListVocId", - table: "TranslateEntity", - column: "VocabularyListVocId"); - migrationBuilder.CreateIndex( name: "IX_TranslateEntityVocabularyEntity_VoctranslationsId", table: "TranslateEntityVocabularyEntity", column: "VoctranslationsId"); + migrationBuilder.CreateIndex( + name: "IX_Translates_VocabularyListVocId", + table: "Translates", + column: "VocabularyListVocId"); + migrationBuilder.CreateIndex( name: "IX_Users_GroupId", table: "Users", @@ -266,14 +266,14 @@ namespace StubbedContextLib.Migrations column: "RoleId"); migrationBuilder.CreateIndex( - name: "IX_VocabularyEntity_LangueName", - table: "VocabularyEntity", - column: "LangueName"); + name: "IX_VocabularyLists_UserId", + table: "VocabularyLists", + column: "UserId"); migrationBuilder.CreateIndex( - name: "IX_VocabularyListEntity_UserId", - table: "VocabularyListEntity", - column: "UserId"); + name: "IX_Vocabularys_LangueName", + table: "Vocabularys", + column: "LangueName"); } /// @@ -286,13 +286,13 @@ namespace StubbedContextLib.Migrations name: "TranslateEntityVocabularyEntity"); migrationBuilder.DropTable( - name: "TranslateEntity"); + name: "Translates"); migrationBuilder.DropTable( - name: "VocabularyEntity"); + name: "Vocabularys"); migrationBuilder.DropTable( - name: "VocabularyListEntity"); + name: "VocabularyLists"); migrationBuilder.DropTable( name: "Langues"); @@ -301,7 +301,7 @@ namespace StubbedContextLib.Migrations name: "Users"); migrationBuilder.DropTable( - name: "GroupEntity"); + name: "Groups"); migrationBuilder.DropTable( name: "Roles"); diff --git a/Project/EntityFramework/StubbedContext/Migrations/StubbedContextModelSnapshot.cs b/Project/EntityFramework/StubbedContext/Migrations/StubbedContextModelSnapshot.cs index 4177cc3..6347fe3 100644 --- a/Project/EntityFramework/StubbedContext/Migrations/StubbedContextModelSnapshot.cs +++ b/Project/EntityFramework/StubbedContext/Migrations/StubbedContextModelSnapshot.cs @@ -34,7 +34,7 @@ namespace StubbedContextLib.Migrations b.HasKey("Id"); - b.ToTable("GroupEntity"); + b.ToTable("Groups"); b.HasData( new @@ -115,7 +115,7 @@ namespace StubbedContextLib.Migrations b.HasIndex("VocabularyListVocId"); - b.ToTable("TranslateEntity"); + b.ToTable("Translates"); b.HasData( new @@ -224,7 +224,7 @@ namespace StubbedContextLib.Migrations b.HasIndex("LangueName"); - b.ToTable("VocabularyEntity"); + b.ToTable("Vocabularys"); b.HasData( new @@ -255,7 +255,7 @@ namespace StubbedContextLib.Migrations b.HasIndex("UserId"); - b.ToTable("VocabularyListEntity"); + b.ToTable("VocabularyLists"); b.HasData( new diff --git a/Project/EntityFramework/StubbedContext/UnitOfWork.cs b/Project/EntityFramework/StubbedContext/UnitOfWork.cs new file mode 100644 index 0000000..0bf1ffd --- /dev/null +++ b/Project/EntityFramework/StubbedContext/UnitOfWork.cs @@ -0,0 +1,197 @@ +using Entities; +using Microsoft.EntityFrameworkCore; +using StubbedContextLib; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DbContextLib +{ + public class UnitOfWork : IDisposable + { + private bool disposed = false; + + private GenericRepository? groupRepository; + + private GenericRepository? langueRepository; + + private GenericRepository? roleRepository; + + private GenericRepository? translateRepository; + + private GenericRepository? userRepository; + + private GenericRepository? vocabularyRepository; + + private GenericRepository? vocabularyListRepository; + + + + + private SAEContext _context { get; set; } + public UnitOfWork(SAEContext context) { + _context = context; + + _context.Database.EnsureCreated(); + } + + public UnitOfWork(StubbedContext context) + { + _context = context; + + _context.Database.EnsureCreated(); + } + + public UnitOfWork(DbContextOptions options) +: this(new StubbedContext(options)) + { + } + + + public UnitOfWork() + : this(new StubbedContext()) + { + } + + protected virtual void Dispose(bool disposing) + { + if (!this.disposed && disposing) + { + _context.Dispose(); + } + this.disposed = true; + } + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + public GenericRepository GroupRepository + { + get + { + if (groupRepository == null) + { + groupRepository = new GenericRepository(_context); + } + return groupRepository; + } + } + + public GenericRepository LangueRepository + { + get + { + if (langueRepository == null) + { + langueRepository = new GenericRepository(_context); + } + return langueRepository; + } + } + + public GenericRepository RoleRepository + { + get + { + if (roleRepository == null) + { + roleRepository = new GenericRepository(_context); + } + return roleRepository; + } + } + + public GenericRepository TranslateRepository + { + get + { + if (translateRepository == null) + { + translateRepository = new GenericRepository(_context); + } + return translateRepository; + } + } + + public GenericRepository UserRepository + { + get + { + if (userRepository == null) + { + userRepository = new GenericRepository(_context); + } + return userRepository; + } + } + + public GenericRepository VocabularyRepository + { + get + { + if (vocabularyRepository == null) + { + vocabularyRepository = new GenericRepository(_context); + } + return vocabularyRepository; + } + } + + public GenericRepository VocabularyListRepository + { + get + { + if (vocabularyListRepository == null) + { + vocabularyListRepository = new GenericRepository(_context); + } + return vocabularyListRepository; + } + } + + public async Task SaveChangesAsync() + { + int result = 0; + try + { + result = await _context.SaveChangesAsync(); + } + catch + { + RejectChanges(); + return -1; + } + foreach (var entity in _context.ChangeTracker.Entries() + .Where(e => e.State != EntityState.Detached)) + { + entity.State = EntityState.Detached; + } + return result; + } + + public void RejectChanges() + { + foreach (var entry in _context.ChangeTracker.Entries() + .Where(e => e.State != EntityState.Unchanged)) + { + switch (entry.State) + { + case EntityState.Added: + entry.State = EntityState.Detached; + break; + case EntityState.Modified: + case EntityState.Deleted: + entry.Reload(); + break; + } + } + } + + + } +} diff --git a/Project/EntityFramework/TU/GroupTU.cs b/Project/EntityFramework/TU/GroupTU.cs index 6670432..4897429 100644 --- a/Project/EntityFramework/TU/GroupTU.cs +++ b/Project/EntityFramework/TU/GroupTU.cs @@ -289,34 +289,8 @@ namespace TU } } - [TestMethod] - public async Task TestAddVocabListToGroup() - { - var connection = new SqliteConnection("DataSource=:memory:"); - connection.Open(); - var options = new DbContextOptionsBuilder() - .UseSqlite(connection) - .Options; - using (var context = new StubbedContext(options)) - { - context.Database.EnsureCreated(); - var mockLogger = new Mock>(); - - var controller = new GroupController(new GroupService(context), mockLogger.Object); - - var result = await controller.AddVocabularyListToGroup(1, 1); - Assert.IsNotNull(result.Value); - Assert.AreEqual(1, result.Value.Id); - - var test = await context.Groups.FirstOrDefaultAsync(g => g.Id == 1); - var testVocab = await context.VocabularyLists.FirstOrDefaultAsync(g => g.Id == 1); - Assert.IsNotNull(test); - Assert.IsNotNull(testVocab); - Assert.AreEqual(test.GroupVocabularyList.First(), testVocab); - } - } } } \ No newline at end of file diff --git a/Project/EntityFramework/TU/RoleTU.cs b/Project/EntityFramework/TU/RoleTU.cs index 2a94e01..417ea9c 100644 --- a/Project/EntityFramework/TU/RoleTU.cs +++ b/Project/EntityFramework/TU/RoleTU.cs @@ -31,7 +31,7 @@ namespace TU var controller = new RoleController(new RoleService(context), mockLogger.Object); - var newRole = new RoleDTO { Id = 100, Name = "test" }; + var newRole = new RoleDTO { Id = 1, Name = "test" }; var result = await controller.AddRole(newRole); @@ -39,7 +39,7 @@ namespace TU //ici on met 4 pour verifier que le Id n'est pas celui que l'on donne mais bien : CountList + 1 Assert.AreEqual(4, result.Value.Id); Assert.AreEqual("test", result.Value.Name); - var test = await context.Roles.FirstOrDefaultAsync(r => r.Id == 4); + var test = context.Roles.Find((long)4); Assert.IsNotNull(test); } } @@ -60,12 +60,11 @@ namespace TU var mockLogger = new Mock>(); var controller = new RoleController(new RoleService(context), mockLogger.Object); - - var result = await controller.DeleteRole(3); + var result = await controller.DeleteRole(1); Assert.IsNotNull(result.Value); - Assert.AreEqual(3, result.Value.Id); - Assert.AreEqual("Student", result.Value.Name); - var test = await context.Roles.FirstOrDefaultAsync(r => r.Id == 3); + Assert.AreEqual(1, result.Value.Id); + Assert.AreEqual("Admin", result.Value.Name); + var test = context.Roles.Find((long)1); Assert.IsNull(test); } } @@ -86,10 +85,11 @@ namespace TU var controller = new RoleController(new RoleService(context), mockLogger.Object); - var result = await controller.GetRole(3); + + var result = await controller.GetRole((long)1); Assert.IsNotNull(result.Value); - Assert.AreEqual(3, result.Value.Id); - Assert.AreEqual("Student", result.Value.Name); + Assert.AreEqual(1, result.Value.Id); + Assert.AreEqual("Admin", result.Value.Name); } } diff --git a/Project/EntityFramework/TU/TranslateTU.cs b/Project/EntityFramework/TU/TranslateTU.cs index 8d3906a..ca2845f 100644 --- a/Project/EntityFramework/TU/TranslateTU.cs +++ b/Project/EntityFramework/TU/TranslateTU.cs @@ -64,7 +64,6 @@ namespace TU var controller = new TranslateController(new TranslateService(context), mockLogger.Object); - var result = await controller.GetTranslate(1); Assert.IsNotNull(result.Value); Assert.AreEqual(1, result.Value.Id); @@ -148,37 +147,5 @@ namespace TU } } - [TestMethod] - public async Task TestAddVocabToTranslate() - { - var connection = new SqliteConnection("DataSource=:memory:"); - connection.Open(); - var options = new DbContextOptionsBuilder() - .UseSqlite(connection) - .Options; - - using (var context = new StubbedContext(options)) - { - context.Database.EnsureCreated(); - - var mockLogger = new Mock>(); - - var controller = new TranslateController(new TranslateService(context), mockLogger.Object); - var result = await controller.AddVocab("Bonjour", 1); - Assert.IsNotNull(result.Value); - Assert.AreEqual("Bonjour", result.Value.word); - - var res = await context.Translates.FirstOrDefaultAsync(v => v.Id == 1); - Assert.IsNotNull(res); - var test = res.TransVoc.FirstOrDefault(t => t.word == "Bonjour"); - Assert.IsNotNull(test); - Assert.AreEqual("Bonjour", test.word); - - var test2 = await context.TransVoc.FirstOrDefaultAsync(t => t.word == "Bonjour"); - Assert.IsNotNull(test2); - Assert.AreEqual("Bonjour", test2.word); - - } - } } } diff --git a/Project/EntityFramework/TU/VocabularyListTU.cs b/Project/EntityFramework/TU/VocabularyListTU.cs index 3ad2793..443ed30 100644 --- a/Project/EntityFramework/TU/VocabularyListTU.cs +++ b/Project/EntityFramework/TU/VocabularyListTU.cs @@ -179,43 +179,6 @@ namespace TU - } - } - - [TestMethod] - public async Task TestAddGroupToVocabularyList() - { - var connection = new SqliteConnection("DataSource=:memory:"); - connection.Open(); - var options = new DbContextOptionsBuilder() - .UseSqlite(connection) - .Options; - - using (var context = new StubbedContext(options)) - { - context.Database.EnsureCreated(); - - var mockLogger = new Mock>(); - - var controller = new VocabularyListController(new VocabularyListService(context), mockLogger.Object); - - var result = await controller.AddGroupToVocabularyList(1, 1); - Assert.IsNotNull(result.Value); - Assert.AreEqual("informatics", result.Value.sector); - Assert.AreEqual(1, result.Value.Id); - - var res = await context.VocabularyLists.FirstOrDefaultAsync(v => v.Id == 1); - Assert.IsNotNull(res); - var test = res.VocsGroups.FirstOrDefault(g => g.Id == 1); - Assert.IsNotNull(test); - Assert.AreEqual("informatics", test.sector); - Assert.AreEqual(1, test.Id); - var test2 = await context.VocsGroups.FirstOrDefaultAsync(g => g.Id == 1); - Assert.IsNotNull(test2); - Assert.AreEqual("informatics", test2.sector); - Assert.AreEqual(1, test2.Id); - - } } } diff --git a/Project/EntityFramework/TU/VocabularyTU.cs b/Project/EntityFramework/TU/VocabularyTU.cs index 22dea5a..847d2d3 100644 --- a/Project/EntityFramework/TU/VocabularyTU.cs +++ b/Project/EntityFramework/TU/VocabularyTU.cs @@ -174,43 +174,6 @@ namespace TU } } - [TestMethod] - public async Task TestAddTranslation() - { - - var connection = new SqliteConnection("DataSource=:memory:"); - connection.Open(); - var options = new DbContextOptionsBuilder() - .UseSqlite(connection) - .Options; - - using (var context = new StubbedContext(options)) - { - context.Database.EnsureCreated(); - - var mockLogger = new Mock>(); - - var controller = new VocabularyController(new VocabularyService(context), mockLogger.Object); - var result3 = await controller.AddTranslation("Bonjour",1); - Assert.IsNotNull(result3.Value); - Assert.AreEqual(1, result3.Value.Id); - - - var res = await context.Vocabularys.FirstOrDefaultAsync(v => v.word == "Bonjour"); - Assert.IsNotNull(res); - var test = res.Voctranslations.FirstOrDefault(t => t.Id == 1); - Assert.IsNotNull(test); - Assert.AreEqual(1, test.Id); - - - var test2 = await context.Voctranslations.FirstOrDefaultAsync(t => t.Id == 1); - Assert.IsNotNull(test2); - Assert.AreEqual(1, test2.Id); - - - } - } - } } diff --git a/Project/EntityFramework/TestConsole/Program.cs b/Project/EntityFramework/TestConsole/Program.cs index d58ca71..56ed813 100644 --- a/Project/EntityFramework/TestConsole/Program.cs +++ b/Project/EntityFramework/TestConsole/Program.cs @@ -15,21 +15,10 @@ var options = new DbContextOptionsBuilder() .UseSqlite(connection) .Options; Console.WriteLine("Test Users : \n\n"); -using (var context = new StubbedContext(options)) +Console.WriteLine("\n\nTest Users : \n\n"); +using (var uow = new UnitOfWork(options)) { - context.Database.EnsureCreated(); - - var users = context.Users.ToList(); - Console.WriteLine("Users: " + users.Count); - var roles = context.Roles.ToList(); - Console.WriteLine("Roles: " + roles.Count); - - Console.WriteLine("\ntest show 5 first Users : \n"); - foreach (var user in context.Users.Take(5)) - { - Console.WriteLine(user.toString()); - } - + var users = uow.UserRepository; var user1 = new UserEntity { Name = "name4", @@ -43,101 +32,110 @@ using (var context = new StubbedContext(options)) image = "image4", }; - context.Users.Add(user1); - context.SaveChanges(); - - Console.WriteLine("\ntest ajout (1 user suplementaire normalement) \n"); - foreach (var user in context.Users.Take(5)) + users.Insert(user1); + await uow.SaveChangesAsync(); + Console.WriteLine("\ntest ajout (1 user supplémentaire normalement) \n"); + foreach (var user in users.GetItems(0, 5)) { Console.WriteLine(user.toString()); } - user1.Name = "updated"; - context.Users.Update(user1); - context.SaveChanges(); - Console.WriteLine("\ntest update (le nom doit etre 'updated') \n"); + users.Update(user1); + await uow.SaveChangesAsync(); + Console.WriteLine("\ntest update (le nom doit être 'updated') \n"); Console.WriteLine(user1.toString()); - context.Users.Remove(user1); - context.SaveChanges(); + users.Delete(user1); + await uow.SaveChangesAsync(); Console.WriteLine("\ntest suppression\n"); - foreach (var user in context.Users.Take(5)) + foreach (var user in users.GetItems(0, 5)) { Console.WriteLine(user.toString()); } +} - Console.WriteLine("\n\nTest VocsGroups : \n\n"); - var groups = context.Groups.ToList(); - Console.WriteLine("VocsGroups: " + groups.Count); - Console.WriteLine("\ntest show 5 first VocsGroups : \n"); - foreach (var group in context.Groups.Take(5)) +Console.WriteLine("\n\nTest VocsGroups : \n\n"); +using (var uow = new UnitOfWork(options)) +{ + var groups = uow.GroupRepository; + var users = uow.UserRepository; + var user1 = new UserEntity { - Console.WriteLine(group.toString()); - } - + Name = "name4", + UserName = "username4", + NickName = "nickname4", + ExtraTime = true, + GroupId = 1, + Password = "12344", + Email = "", + RoleId = 3, + image = "image4", + }; var group1 = new GroupEntity { - Id = 4, Num = 4, year = 4, sector = "sector4", - Users = [user1], - + Users = new List { user1 } }; - context.Groups.Add(group1); - context.SaveChanges(); + groups.Insert(group1); + await uow.SaveChangesAsync(); - Console.WriteLine("\ntest ajout (1 group suplementaire normalement) \n"); - foreach (var group in context.Groups.Take(5)) + Console.WriteLine("\ntest ajout (1 group supplémentaire normalement) \n"); + foreach (var group in groups.GetItems(0, 5)) { Console.WriteLine(group.toString()); } + group1.Num = 5; group1.sector = "updated"; - context.Update(group1); - context.SaveChanges(); - Console.WriteLine("\ntest update (le nom doit etre 'updated' et le Num = 5) \n"); + groups.Update(group1); + await uow.SaveChangesAsync(); + Console.WriteLine("\ntest update (le nom doit être 'updated' et le Num = 5) \n"); Console.WriteLine(group1.toString()); Console.WriteLine("\n test utilisateur du groupe normalement le user : updated "); - foreach (var group in context.Groups.Take(5)) + foreach (var group in groups.GetItems(0, 5)) { - foreach (var user in group.Users.Take(5)) + foreach (var user in users.GetItems(0, 5)) { Console.WriteLine(user.toString()); } } - context.Remove(group1); - context.SaveChanges(); + groups.Delete(group1); + await uow.SaveChangesAsync(); Console.WriteLine("\ntest suppression\n"); - foreach (var group in context.Groups.Take(5)) + foreach (var group in groups.GetItems(0, 5)) { Console.WriteLine(group.toString()); } +} - Console.WriteLine("\n\nTest Langue : \n\n"); +Console.WriteLine("\n\nTest Langue : \n\n"); +using (var uow = new UnitOfWork(options)) +{ + var langues = uow.LangueRepository; - context.Database.EnsureCreated(); - var langues = context.Langues.ToList(); - Console.WriteLine("Langues: " + langues.Count); Console.WriteLine("\ntest show 5 first Langues : \n"); - foreach (var langue in context.Langues.Take(5)) + foreach (var langue in langues.GetItems(0, 5)) { Console.WriteLine(langue.name); } + Console.WriteLine("\n ajout Langue (normalement chinese\n"); var langue1 = new LangueEntity { name = "Chinese" }; - context.Langues.Add(langue1); - context.SaveChanges(); - foreach (var langue in context.Langues.Take(5)) + langues.Insert(langue1); + await uow.SaveChangesAsync(); + foreach (var langue in langues.GetItems(0, 5)) { Console.WriteLine(langue.name); } + Console.WriteLine("\n test des liens langues <=> vocabulaires (resultat attendu : 'word1 Chinese'\n"); var vocabularyList1 = new VocabularyEntity { @@ -145,205 +143,200 @@ using (var context = new StubbedContext(options)) LangueName = "Chinese", Langue = langue1 }; - context.Vocabularys.Add(vocabularyList1); - foreach (var langue in context.Langues.Take(5)) + uow.VocabularyRepository.Insert(vocabularyList1); + await uow.SaveChangesAsync(); + foreach (var langue in langues.GetItems(0, 5)) { - foreach (var vocabularyList in langue.vocabularys.Take(5)) + foreach (var vocabularyList in langue.vocabularys) { Console.WriteLine(vocabularyList.toString()); - } } - context.Langues.Remove(langue1); - context.SaveChanges(); + langues.Delete(langue1); + await uow.SaveChangesAsync(); Console.WriteLine("\ntest suppression (il n'y a normalement plus la langue 'Chinese'\n"); - foreach (var langue in context.Langues.Take(5)) + foreach (var langue in langues.GetItems(0, 5)) { Console.WriteLine(langue.name); } - Console.WriteLine("\n\nTest Roles : \n\n"); - context.Database.EnsureCreated(); - var roles2 = context.Roles.ToList(); - Console.WriteLine("Roles: " + roles2.Count); +} + +Console.WriteLine("\n\nTest Roles : \n\n"); +using (var uow = new UnitOfWork(options)) +{ + var roles = uow.RoleRepository; + Console.WriteLine("\ntest show 5 first Roles : \n"); - foreach (var role in context.Roles.Take(5)) + foreach (var role in roles.GetItems(0, 5)) { Console.WriteLine(role.toString()); } + var role1 = new RoleEntity { - Id = 4, Name = "Role4" }; - context.Roles.Add(role1); - context.SaveChanges(); + roles.Insert(role1); + await uow.SaveChangesAsync(); Console.WriteLine("\n ajout Role (normalement Role4\n"); - foreach (var role in context.Roles.Take(5)) + foreach (var role in roles.GetItems(0, 5)) { Console.WriteLine(role.toString()); } + role1.Name = "updated"; - context.Roles.Update(role1); - context.SaveChanges(); - Console.WriteLine("\ntest update (le nom doit etre 'updated') \n"); + roles.Update(role1); + await uow.SaveChangesAsync(); + Console.WriteLine("\ntest update (le nom doit être 'updated') \n"); Console.WriteLine(role1.toString()); - Console.WriteLine("\n test utilisateur du role normalement"); - foreach (var role in context.Roles.Take(5)) + foreach (var role in roles.GetItems(0, 5)) { - foreach (var user in role.Users.Take(5)) + foreach (var user in role.Users) { Console.WriteLine(user.toString()); } } - context.Roles.Remove(role1); - context.SaveChanges(); + roles.Delete(role1); + await uow.SaveChangesAsync(); Console.WriteLine("\ntest suppression (il n'y a normalement plus le role 'Role4'\n"); - foreach (var role in context.Roles.Take(5)) + foreach (var role in roles.GetItems(0, 5)) { Console.WriteLine(role.toString()); } - - Console.WriteLine("\n\nTest Translate : \n\n"); - context.Database.EnsureCreated(); - var translates = context.Translates.ToList(); - Console.WriteLine("Translates: " + translates.Count); +} + +Console.WriteLine("\n\nTest Translate : \n\n"); +using (var uow = new UnitOfWork(options)) +{ + var translates = uow.TranslateRepository; + Console.WriteLine("\ntest show 5 first Translates : \n"); - foreach (var translate in context.Translates.Take(5)) + foreach (var translate in translates.GetItems(0, 5)) { Console.WriteLine(translate.toString()); } + var translate1 = new TranslateEntity { - Id = 4, WordsId = "Bonjour", VocabularyListVocId = 1 -}; - context.Translates.Add(translate1); - context.SaveChanges(); + }; + translates.Insert(translate1); + await uow.SaveChangesAsync(); Console.WriteLine("\n ajout Translate (normalement word4\n"); - foreach (var translate in context.Translates.Take(5)) + foreach (var translate in translates.GetItems(0, 5)) { Console.WriteLine(translate.toString()); } + var translate2 = new VocabularyEntity { word = "word4", LangueName = "English", }; - context.Vocabularys.Add(translate2); - context.SaveChanges(); + uow.VocabularyRepository.Insert(translate2); + await uow.SaveChangesAsync(); translate1.WordsId = "word4"; - context.Translates.Update(translate1); - context.SaveChanges(); - Console.WriteLine("\ntest update (le mot doit etre 'updated') \n"); + translates.Update(translate1); + await uow.SaveChangesAsync(); + Console.WriteLine("\ntest update (le mot doit être 'updated') \n"); Console.WriteLine(translate1.toString()); - context.Translates.Remove(translate1); - context.SaveChanges(); + translates.Delete(translate1); + await uow.SaveChangesAsync(); Console.WriteLine("\ntest suppression (il n'y a normalement plus le mot 'word4'\n"); - foreach (var translate in context.Translates.Take(5)) + foreach (var translate in translates.GetItems(0, 5)) { Console.WriteLine(translate.toString()); } - Console.WriteLine("\n\nTest Vocabulary : \n\n"); - context.Database.EnsureCreated(); +} + +Console.WriteLine("\n\nTest Vocabulary : \n\n"); +using (var uow = new UnitOfWork(options)) +{ + var vocabularies = uow.VocabularyRepository; - var vocabularys = context.Vocabularys.ToList(); - Console.WriteLine("Vocabularys: " + vocabularys.Count); Console.WriteLine("\ntest show 5 first Vocabularys : \n"); - foreach (var vocabulary in context.Vocabularys.Take(5)) + foreach (var vocabulary in vocabularies.GetItems(0, 5)) { Console.WriteLine(vocabulary.toString()); } - var vocabulary1 = new VocabularyEntity - { + + var vocabulary1 = new VocabularyEntity + { word = "NewWord", LangueName = "English" }; - context.Vocabularys.Add(vocabulary1); - context.SaveChanges(); + vocabularies.Insert(vocabulary1); + await uow.SaveChangesAsync(); Console.WriteLine("\n ajout Vocabulary (normalement NewWord) \n"); - foreach (var vocabulary in context.Vocabularys.Take(5)) + foreach (var vocabulary in vocabularies.GetItems(0, 5)) { Console.WriteLine(vocabulary.toString()); } + vocabulary1.LangueName = "French"; - context.Vocabularys.Update(vocabulary1); - context.SaveChanges(); - Console.WriteLine("\ntest update (la langue doit etre 'French') \n"); + vocabularies.Update(vocabulary1); + await uow.SaveChangesAsync(); + Console.WriteLine("\ntest update (la langue doit être 'French') \n"); Console.WriteLine(vocabulary1.toString()); - context.Vocabularys.Remove(vocabulary1); - context.SaveChanges(); + vocabularies.Delete(vocabulary1); + await uow.SaveChangesAsync(); Console.WriteLine("\ntest suppression (il n'y a normalement plus le mot 'NewWord'\n"); - foreach (var vocabulary in context.Vocabularys.Take(5)) + foreach (var vocabulary in vocabularies.GetItems(0, 5)) { Console.WriteLine(vocabulary.toString()); } +} + +Console.WriteLine("\n\nTest GroupVocabularyList : \n\n"); +using (var uow = new UnitOfWork(options)) +{ + var vocabularyLists = uow.VocabularyListRepository; - Console.WriteLine("\n\nTest GroupVocabularyList : \n\n"); - context.Database.EnsureCreated(); - var vocabularyLists = context.VocabularyLists.ToList(); - Console.WriteLine("VocabularyLists: " + vocabularyLists.Count); Console.WriteLine("\ntest show 5 first VocabularyLists : \n"); - foreach (var vocabularyList in context.VocabularyLists.Take(5)) + foreach (var vocabularyList in vocabularyLists.GetItems(0, 5)) { Console.WriteLine(vocabularyList.toString()); } + var vocabularyList2 = new VocabularyListEntity { - Id = 4, Name = "name4", Image = "image4", UserId = 3 }; - context.VocabularyLists.Add(vocabularyList2); - context.SaveChanges(); + vocabularyLists.Insert(vocabularyList2); + await uow.SaveChangesAsync(); Console.WriteLine("\n ajout GroupVocabularyList (normalement name4) \n"); - foreach (var vocabularyList in context.VocabularyLists.Take(5)) + foreach (var vocabularyList in vocabularyLists.GetItems(0, 5)) { Console.WriteLine(vocabularyList.toString()); } + vocabularyList2.Name = "updated"; - context.VocabularyLists.Update(vocabularyList2); - context.SaveChanges(); - Console.WriteLine("\ntest update (le nom doit etre 'updated') \n"); + vocabularyLists.Update(vocabularyList2); + await uow.SaveChangesAsync(); + Console.WriteLine("\ntest update (le nom doit être 'updated') \n"); Console.WriteLine(vocabularyList2.toString()); + Console.WriteLine("\n test affichage des owner (user) des listes normalement"); - foreach (var vocabularyList in context.VocabularyLists.Take(5)) + foreach (var vocabularyList in vocabularyLists.GetItems(0, 5)) { - - Console.WriteLine(vocabularyList.User.toString()); + if(vocabularyList.User != null) + Console.WriteLine(vocabularyList.User.toString()); } - - context.VocabularyLists.Remove(vocabularyList2); - context.SaveChanges(); + + vocabularyLists.Delete(vocabularyList2); + await uow.SaveChangesAsync(); Console.WriteLine("\ntest suppression (il n'y a normalement plus la liste 'name4'\n"); - foreach (var vocabularyList in context.VocabularyLists.Take(5)) + foreach (var vocabularyList in vocabularyLists.GetItems(0, 5)) { Console.WriteLine(vocabularyList.toString()); } - - Console.WriteLine("\n\nTest Many to Many (si pas d'erreur alors test reussi) : \n\n"); - - context.Database.EnsureCreated(); - var groupVoc = new GroupEntity { Id = 2, Num = 1, year = 1, sector = "sector1" }; - VocabularyListEntity VocListGroup = new VocabularyListEntity { Id = 2, Name = "name1", Image = "image1", UserId = 1 }; - context.AddRange(groupVoc, VocListGroup); - context.SaveChanges(); - - var transVoc = new TranslateEntity { Id = 2, WordsId = "1", VocabularyListVocId = 1 }; - var VocTrans = new VocabularyEntity { word = "Test", LangueName = "French" }; - context.AddRange(transVoc, VocTrans); - context.SaveChanges(); - - - - - - +} -} \ No newline at end of file