Infrasctructure: Add StreetRepository
This commit is contained in:
parent
226e5e4e3e
commit
c3567fcd59
86
src/Infrastructure/StreetRepository.cs
Normal file
86
src/Infrastructure/StreetRepository.cs
Normal file
@ -0,0 +1,86 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using NetTopologySuite.Geometries;
|
||||
|
||||
public class StreetRepository
|
||||
{
|
||||
private readonly StreetDbContext Context;
|
||||
|
||||
public StreetRepository(StreetDbContext context)
|
||||
{
|
||||
Context = context;
|
||||
}
|
||||
|
||||
public async Task<Street> GetByNameAsync(string name)
|
||||
{
|
||||
return await Context.Streets.FirstOrDefaultAsync(s => s.Name == name);
|
||||
}
|
||||
|
||||
public async Task<bool> ExistsAsync(string name)
|
||||
{
|
||||
return await Context.Streets.AnyAsync(s => s.Name == name);
|
||||
}
|
||||
|
||||
public async Task AddAsync(Street street)
|
||||
{
|
||||
await Context.Streets.AddAsync(street);
|
||||
await Context.SaveChangesAsync();
|
||||
}
|
||||
|
||||
public async Task<bool> RemoveAsync(string name)
|
||||
{
|
||||
var street = await GetByNameAsync(name);
|
||||
if (street == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
Context.Streets.Remove(street);
|
||||
await Context.SaveChangesAsync();
|
||||
return true;
|
||||
}
|
||||
|
||||
public async Task UpdateGeometryInBackend(string name, Geometry point)
|
||||
{
|
||||
var street = await GetByNameAsync(name);
|
||||
|
||||
if (street == null)
|
||||
{
|
||||
throw new KeyNotFoundException($"Street '{name}' not found.");
|
||||
}
|
||||
|
||||
street.AddPointToGeometry(point.Coordinate);
|
||||
|
||||
try
|
||||
{
|
||||
await Context.SaveChangesAsync();
|
||||
}
|
||||
catch (DbUpdateConcurrencyException)
|
||||
{
|
||||
throw new InvalidOperationException("Concurrency conflict: The street was modified by another transaction.");
|
||||
}
|
||||
}
|
||||
|
||||
public async Task UpdateGeometryWithPostGIS(string name, Geometry point)
|
||||
{
|
||||
var street = await GetByNameAsync(name);
|
||||
|
||||
if (street == null)
|
||||
{
|
||||
throw new KeyNotFoundException($"Street '{name}' not found.");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
// PostgreSQL's UPDATE already checks for concurrency by default
|
||||
await Context.Database.ExecuteSqlRawAsync(
|
||||
"UPDATE \"Streets\" SET \"Geometry\" = ST_AddPoint(\"Geometry\", ST_SetSRID(ST_MakePoint({0}, {1}), 4326)) WHERE \"Name\" = {2}",
|
||||
point.Coordinate.X, point.Coordinate.Y, name
|
||||
);
|
||||
|
||||
}
|
||||
catch (DbUpdateConcurrencyException)
|
||||
{
|
||||
throw new InvalidOperationException("Concurrency conflict: The street was modified by another transaction.");
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user