EntityFrameworkで、 intSaveChangesAsync()
を返します。だから、そうであるかどうかを確認することができます。> 0
何かが起こった場合SaveChangesAsync()
、影響を受けた行の数が返されます。これはif value > 0
、trueを意味します。簡単に言うと、以下のシーンリオを使用できます。
入れる
public Task<bool> CreateEntity(Entity entity){
if(entity == null)
return false;
await _dataContext.Entities.AddAsync(entity);
var created = await _dataContext.SaveChangesAsync();
return created > 0;
}
アップデート
public async Task<bool> UpdateEntity(Entity entityToUpdate)
{
if(entityToUpdate == null)
return false;
_dataContext.Posts.Update(entityToUpdate);
var updated = await _dataContext.SaveChangesAsync();
return updated > 0;
}
消去
public async Task<bool> DeleteEntity(int entityId)
{
var entity = await _dataContext.Entities.FindAsync(entityId);
if (entity == null)
return false;
_dataContext.Entities.Remove(entity);
var deleted = await _dataContext.SaveChangesAsync();
return deleted > 0;
}
そして、あなたのメソッドでは、その変更が成功したかどうかを簡単に確認できます。
単純なMVCシーンリオの場合:
public Task<IActionResult> CreateEntity(EntityModel model)
{
if(model == null)
return StatusCode(404);
var entity = new Entity
{
attribute1 = model.attribute1,
attribute2 = model.attribute3
};
var isCreated = await _entityService.CreateEntity(entity);
if(isCreated)
{
//do something and return a view.
}
else
{
//you can return a status code, or an error view.
}
}
更新と削除についても同じ方法を実行できます