我正在尝试实现一种在 foreach 循环中执行存储过程的方法,但我不断收到错误消息,提示“已添加具有相同键的项目。键:StudentId”
控制器
[HttpPost("{id}/link-to-subjects")]
public async Task<ActionResult> LinkStudentToSubjects(int id, int[] subjectIds)
{
try
{
await _studentRepository.LinkStudentToSubjectsAsync(id, subjectIds);
return NoContent();
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
调用存储过程的存储库方法
public async Task<bool> LinkStudentToSubjectsAsync(int studentId, int[] subjectIds)
{
DeleteSubjectStudentLinks(studentId);
var parameters = new Dictionary<string, object>();
foreach (var subjectId in subjectIds)
{
parameters.Add(StoredProcedures.Params.StudentId, studentId);
parameters.Add(StoredProcedures.Params.SubjectId, subjectId);
linkResult = await _repository.ExecuteStoredProcAsync<StudentSubject>(StoredProcedures.LinkStudentSubjects, parameters);
}
if (linkResult is not null)
{
return true;
}
return false;
}
存储过程
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROC [dbo].[LinkStudentSubjects]
@StudentSubjectID int,
@StudentID int,
@SubjectID int
AS
DECLARE @ID int
DECLARE @TableTestID TABLE (ID int)
BEGIN
DECLARE @TableStudentSubjectID TABLE (ID int)
--IF NOT EXISTS (SELECT StudentID , SubjectID FROM [dbo].[StudentSubjects]
--WHERE StudentID = @StudentID)
BEGIN
INSERT into [dbo].[StudentSubjects] (StudentId, SubjectId)
OUTPUT inserted.id INTO @TableStudentSubjectID(ID)
VALUES (@StudentID, @SubjectID)
SELECT ID from @TableStudentSubjectID
END
END
更改您的代码
public async Task<bool> LinkStudentToSubjectsAsync(int studentId, int[] subjectIds)
{
DeleteSubjectStudentLinks(studentId);
var parameters = new Dictionary<string, object>();
foreach (var subjectId in subjectIds)
{
parameters.Add(StoredProcedures.Params.StudentId, studentId);
parameters.Add(StoredProcedures.Params.SubjectId, subjectId);
linkResult = await _repository.ExecuteStoredProcAsync<StudentSubject>(StoredProcedures.LinkStudentSubjects, parameters);
}
if (linkResult is not null)
{
return true;
}
return false;
}
到
public async Task<bool> LinkStudentToSubjectsAsync(int studentId, int[] subjectIds)
{
DeleteSubjectStudentLinks(studentId);
var parameters = new Dictionary<string, object>();
foreach (var subjectId in subjectIds)
{
parameters.Clear();
parameters.Add(StoredProcedures.Params.StudentId, studentId);
parameters.Add(StoredProcedures.Params.SubjectId, subjectId);
linkResult = await _repository.ExecuteStoredProcAsync<StudentSubject>(StoredProcedures.LinkStudentSubjects, parameters);
}
if (linkResult is not null)
{
return true;
}
return false;
}
原因
您定义的
new Dictionary<string, object>();
位于foreach循环之外,因此第一次执行后,之前的studentId
将存在于字典中。解决这个问题的方法是在执行存储过程之前清除之前的记录或者在循环中定义new Dictionary
。