[英]Rest API data doesn't delete
我在 API 上進行簡單的 crud 操作。 我的 GET、POST、PUT 都運行良好。 但是 DELETE 方法不起作用。 它顯示一條錯誤消息:
DELETE 語句與 REFERENCE 約束“FK_Configurations_Mobiles_MobileId”沖突。 沖突發生在數據庫“TestPrime2”、表“dbo.Configurations”、“MobileId”列中。
這里 Mobile class 和 Configurations class 它們是一對多的關系。
[Route("api/[controller]")]
[ApiController]
public class MobilesController : ControllerBase
{
private readonly TestContext _context;
public MobilesController(TestContext context)
{
_context = context;
}
[HttpGet]
public async Task<ActionResult<IEnumerable<Mobile>>> GetMobiles()
{
return await _context.Mobiles.Include(p => p.Configuration).ToListAsync();
}
[HttpGet("{id}")]
public async Task<ActionResult<Mobile>> GetMobile(int id)
{
if(id <= 0)
{
return BadRequest();
}
var mobile = await _context.Mobiles
.Include(p => p.Configuration)
.Where( x => x.Id == id).FirstOrDefaultAsync();
if (mobile == null)
{
return NotFound();
}
return mobile;
}
[HttpPut("{id}")]
public async Task<IActionResult> PutMobile(int id, Mobile mobile)
{
if (id != mobile.Id)
{
return BadRequest();
}
_context.Entry(mobile).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!MobileExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
[HttpPost]
public async Task<ActionResult<Mobile>> PostMobile(Mobile mobile)
{
_context.Mobiles.Add(mobile);
await _context.SaveChangesAsync();
return CreatedAtAction("GetMobile", new { id = mobile.Id }, mobile);
}
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteMobile(int id)
{
if(id <= 0)
{
return BadRequest();
}
var mobile = await _context.Mobiles.FindAsync(id);
if (mobile == null)
{
return NotFound();
}
_context.Mobiles.Remove(mobile);
await _context.SaveChangesAsync();
return NoContent();
}
private bool MobileExists(int id)
{
return _context.Mobiles.Any(e => e.Id == id);
}
}
沒有 DELETE 方法,所有方法都可以正常工作
您需要先從 Configurations 表中刪除所有帶有 MobileId 的條目。
它會是這樣的:
_context.RemoveRange(_context.Configurations.Where(x => x.MobileId == id).ToList());
然后您可以從 Mobile 表中刪除 Mobile。
這是因為您的表中名為 TestPrime2 的外鍵 MobileId 引用了您嘗試刪除的行。
如果您刪除 TestPrime2 表中具有您嘗試刪除的 MobileId 的那一行,它將起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.