0
J'ai créé ce GenericController pour déplacer toutes les logiques CRUD à GenericController, et je piraté des trucs pour le faire fonctionner comme:Supprimer les hacks de mon contrôleur de base générique odata?
- Créer TableForT pour définir l'entité
- Créer une interface IndexedModel pour maintenir GUID pour faire Compraion
- coder en dur le contexte DB
Comment puis-je supprimer ces hacks de mon code pour garder mon propre code?
namespace AirVinyl.API.Controllers
{
public class GenericController<T> : ODataController where T : class, IndexedModel
{
AirVinylDbContext db = new AirVinylDbContext();
private bool Exists(long key)
{
return TableForT().Any(p => p.Id.Equals(key));
}
private DbSet<T> TableForT()
{
return db.Set<T>();
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
[EnableQuery] // EnableQuery allows filter, sort, page, top, etc.
public IQueryable<T> Get()
{
return TableForT();
}
[EnableQuery]
public SingleResult<T> Get([FromODataUri] long key)
{
IQueryable<T> result = Get().Where(p => p.Id.Equals(key));
return SingleResult.Create(result);
}
public async Task<IHttpActionResult> Post(T obj)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
TableForT().Add(obj);
await db.SaveChangesAsync();
return Created(obj);
}
public async Task<IHttpActionResult> Patch([FromODataUri] long key, Delta<T> delta)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var entity = await TableForT().FindAsync(key);
if (entity == null)
{
return NotFound();
}
delta.Patch(entity);
try
{
await db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!Exists(key))
{
return NotFound();
}
else
{
throw;
}
}
return Updated(entity);
}
public async Task<IHttpActionResult> Put([FromODataUri] long key, T obj)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (key.Equals(obj.Id) == false)
{
return BadRequest();
}
db.Entry(obj).State = EntityState.Modified;
try
{
await db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!Exists(key))
{
return NotFound();
}
else
{
throw;
}
}
return Updated(obj);
}
public async Task<IHttpActionResult> Delete([FromODataUri] long key)
{
var entity = await TableForT().FindAsync(key);
if (entity == null)
{
return NotFound();
}
TableForT().Remove(entity);
await db.SaveChangesAsync();
return StatusCode(HttpStatusCode.NoContent);
}
}
}