Skip to content

Commit

Permalink
Make package statistic upsert atomic
Browse files Browse the repository at this point in the history
EF Core does not support upsert out of the box, see dotnet/efcore#4526

But Artiom Chilaru created a NuGet package (FlexLabs.EntityFrameworkCore.Upsert) that handle upsert for PostgreSQL/Sqlite, SqlServer and MySQL.
  • Loading branch information
0xced committed Nov 20, 2019
1 parent 3bc9e7f commit 49561db
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 15 deletions.
25 changes: 10 additions & 15 deletions source/Web/Features/Statistics/StatisticsRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,22 +42,17 @@ public async Task AddStatisticsForResultAsync(InvestigationResult result, Cancel
private async Task AddStatisticAsync(PackageResult package, CancellationToken cancellationToken)
{
await using var context = _contextFactory();
var packageStatistic = await context.PackageStatistics.FindAsync(new object[] {package.PackageName}, cancellationToken);
if (packageStatistic == null)
var packageStatistic = new PackageStatistic
{
context.PackageStatistics.Add(new PackageStatistic
{
Name = package.PackageName,
Count = 1,
LatestSupportType = package.SupportType
});
}
else
{
packageStatistic.Count += 1;
packageStatistic.LatestSupportType = package.SupportType;
}
await context.SaveChangesAsync(cancellationToken);
Name = package.PackageName,
Count = 1,
LatestSupportType = package.SupportType
};
await context.PackageStatistics
.Upsert(packageStatistic)
.On(p => p.Name)
.WhenMatched(p => new PackageStatistic { Count = p.Count + 1 })
.RunAsync(cancellationToken);
}

public async Task<IReadOnlyList<PackageStatistic>> GetAllPackageStatisticsAsync(CancellationToken cancellationToken)
Expand Down
1 change: 1 addition & 0 deletions source/Web/Web.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="FlexLabs.EntityFrameworkCore.Upsert" Version="3.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="3.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="3.0.0" />
Expand Down

0 comments on commit 49561db

Please sign in to comment.