我的主要问题在于这个错误:
SqlException:DELETE语句与REFERENCE约束“FK_Predbilježba_Seminar_SeminarID”冲突。冲突发生在数据库“aspnet-SeminarskiRad-79DF16A9-A226-4056-9182-4A843CF2FF27”,表“dbo.Predbilježba”,列'SeminarID'中。该语句已终止。
System.Data.SqlClient.SqlCommand + <>℃。 ExecuteDbDataReaderAsync> b__122_0(任务结果) DbUpdateException:更新条目时发生错误。有关详细信息,请参阅内部异常
Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection,CancellationToken cancellationToken)
这是第1课
public class Predbilježba
{
[Key]
public int PredbilježbeID { get; set; }
[Required]
[StringLength(50, MinimumLength = 1)]
public string Ime { get; set; }
[Required]
[StringLength(50, MinimumLength = 1)]
public string Prezime { get; set; }
[Required]
[StringLength(50, MinimumLength = 1)]
public string Adresa { get; set; }
[Required]
[StringLength(50, MinimumLength = 1)]
public string Email { get; set; }
[Required]
[StringLength(13, MinimumLength = 9,)]
public string Telefon { get; set; }
public bool Status { get; set; }
[DataType(DataType.Date)]
public DateTime DatumUpisa { get; set; }
public int? SeminarID { get; set; }
public Seminar Seminar { get; set; }
}
第2课
public class Seminar
{
[Key]
public int SeminarID { get; set; }
[StringLength(50, MinimumLength = 3)]
public string Naziv { get; set; }
[StringLength(50, MinimumLength = 3)]
public string Opis { get; set; }
[DataType(DataType.Date)]
public DateTime Datum { get; set; }
public bool Popunjen { get; set; }
public ICollection<Predbilježba> Predbilježba { get; set; }
}
问题是当我在控制器中调用Delete
方法时。但Edit
方法工作,以及Create
方法。
这是Delete
控制器的一部分:
// GET: Seminari/Delete/5
[Authorize]
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var seminar = await _context.Seminari
.FirstOrDefaultAsync(m => m.SeminarID == id);
if (seminar == null)
{
return NotFound();
}
return View(seminar);
}
// POST: Seminari/Delete/5
[Authorize]
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var seminar = await _context.Seminari.FindAsync(id);
_context.Seminari.Remove(seminar);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool SeminarExists(int id)
{
return _context.Seminari.Any(e => e.SeminarID == id);
}
你试图删除Seminar
,但有一个Predbilježba
通过Seminar
属性指向SeminarID
。在删除Predbilježba
之前,您必须将SeminarID
的null
设置为Predbilježba
或删除Seminar
。
这里的问题是您正在尝试删除其主键在另一个表中作为外键引用的记录。您应该首先删除子记录(外键),然后删除主表