我有一个测验SQL模式,我也在使用 ASP.NET 身份。当我尝试将用户的答案插入UserAnswer表时,出现以下错误。似乎它正在尝试插入到用户表中,但我不想要那个?
违反主键约束"PK_AspNetUsers"。无法插入 对象'dbo'中的重复键。AspNetUsers'。重复的键值为 (71ddfebf-18ba-4214-a01e-42ca0f239804(。 无法插入显式值 设置IDENTITY_INSERT时,用于表"问题"中的身份列 到关闭。该语句已终止。
foreach (ProfileViewModel pvm in profileViewModels)
{
UserAnswer ua = new UserAnswer();
ua.QuestionId.ID = pvm.Question.ID;
ua.ApplicationUser.Id = userId;
ua.AnswerText = pvm.Answer;
_userAnswerRepository.Create(ua);
}
这只会
protected void Save() => _context.SaveChanges();
模型是
public class UserAnswer
{
public UserAnswer()
{
this.QuestionId = new Question();
this.ApplicationUser = new ApplicationUser();
}
public int Id { get; set; }
public ApplicationUser ApplicationUser { get; set; }
public Question QuestionId { get; set; }
public string AnswerText { get; set; }
}
我想出于某种原因我需要使用虚拟对象而不是实际对象。该模型看起来不错,但似乎混淆了更新
public class UserAnswer
{
public UserAnswer()
{
this.Question = new Question();
this.User = new ApplicationUser();
}
public int Id { get; set; }
public string UserId { get; set; } // FK to ApplicationUser
public int QuestionId { get; set; } // FK to Question
public string AnswerText { get; set; }
public virtual Question Question { get; set; }
public virtual ApplicationUser User { get; set; }
}