内部异常错误:INSERT语句与FOREIGN KEY约束冲突

时间:2019-01-14 13:20:10

标签: asp.net-mvc insert foreign-keys constraints inner-exception

我试图将票证表的ID添加到另一个表(TrackTicket)并将其插入到字段(TicketId)中,但出现此错误

错误:EntityFramework.dll中发生了'System.Data.Entity.Infrastructure.DbUpdateException'类型的异常,但未在用户代码中处理

-内部异常错误:插入语句与外键约束\“ FK_dbo.TrackTickets_dbo.Tickets_TicketId \”冲突。数据库\“数据库名称” \“,表\” dbo.Tickets“ \列“ Id”中发生冲突。\该语句已终止

是什么意思?救命!

代码

控制器

_context.Tickets.Add(new Ticket {ClientId = userId , Subject = viewModel.Ticket.Subject, TypeOfTicket = viewModel.Ticket.TypeOfTicket, ConcernedDept = viewModel.Ticket.ConcernedDept, Date = DateTime.Now});

_context.TicketContents.Add(new TicketContent {Subject = viewModel.Ticket.Subject, Content = viewModel.TicketContent.Content});

_context.TrackTickets.Add(new TrackTicket { ClientId = userId,TicketId = viewModel.Ticket.Id  ,StatusHelpDesk = "Received", DateHelpDeskReceived = DateTime.Now });

_context.SaveChanges();

1 个答案:

答案 0 :(得分:0)

我不完全了解您的方案,但是您正在创建或插入新的票证,并且还在未设置或检索票证ID的情况下创建或插入引用票证的跟踪票证。

此行尚无ID。您可以在此处设置ID,也可以创建变量票证,然后使用该ID链接到TrackTickets。     _context.Tickets.Add(新票证{ClientId = userId,Subject = viewModel.Ticket.Subject,TypeOfTicket = viewModel.Ticket.TypeOfTicket,ConcernedDept = viewModel.Ticket.ConcernedDept,Date = DateTime.Now});

添加操作将失败,因为无法将TicketId链接到某些内容(未插入具有该ID的票证。

_context.TrackTickets.Add(new TrackTicket { ClientId = userId, TicketId = viewModel.Ticket.Id, StatusHelpDesk = "Received", DateHelpDeskReceived = DateTime.Now });

如果自动生成ticketId,可以使用以下方法:

var newTicket = new Ticket {ClientId = userId, Subject = viewModel.Ticket.Subject, TypeOfTicket = viewModel.Ticket.TypeOfTicket, ConcernedDept = viewModel.Ticket.ConcernedDept, Date = DateTime.Now}  
_context.Tickets.Add(newTicket);
_context.SaveChanges();

如果现在重用newTicket对象,它将有一个ID。因此,在trackTickets的添加中,使用newTicket的ID

_context.TrackTickets.Add(new TrackTicket { ClientId = userId, TicketId = newTicket.Id, StatusHelpDesk = "Received", DateHelpDeskReceived = DateTime.Now });

如果不自动生成票证ID,则必须在创建票证(添加到上下文)中设置ID:

var newTicket = new Ticket { Id = viewModel.Ticket.Id, ClientId = userId, Subject = viewModel.Ticket.Subject, TypeOfTicket = viewModel.Ticket.TypeOfTicket, ConcernedDept = viewModel.Ticket.ConcernedDept, Date = DateTime.Now}