代码之家  ›  专栏  ›  技术社区  ›  punkouter

使用标识类时EF core savecontext出错

  •  -1
  • punkouter  · 技术社区  · 7 年前

    我有一个测验sql模式,我也在使用ASP。网络标识。当我尝试将用户的答案插入到UserAnswer表中时,会出现以下错误。它似乎试图插入到用户表中,但我不想这样做?

    违反主键约束“PK\u AspNetUsers”。无法插入 对象“dbo”中的键重复。AspNetUsers’。重复键值为 (71ddfebf-18ba-4214-a01e-42ca0f239804)。无法插入显式值 设置identity\u INSERT时,用于表“Questions”中的identity列 关闭。该语句已终止。

    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; }
    }
    
    1 回复  |  直到 7 年前
        1
  •  -1
  •   punkouter    7 年前

    我想出于某种原因,我需要使用虚拟对象而不是实际对象。。模型看起来不错,但似乎混淆了更新

     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; }
    }