Search code examples
asp.net-coreasp.net-identityentity-framework-core

Error with EF core savecontext using Identity class


I have a quiz sql schema and I am also using ASP.NET Identity. When I attempt to insert an answer from the user into the UserAnswer table I get the error below. It seems like it is trying to insert into the User table but I don't want that?

Violation of PRIMARY KEY constraint 'PK_AspNetUsers'. Cannot insert duplicate key in object 'dbo.AspNetUsers'. The duplicate key value is (71ddfebf-18ba-4214-a01e-42ca0f239804). Cannot insert explicit value for identity column in table 'Questions' when IDENTITY_INSERT is set to OFF. The statement has been terminated.

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

which just does

protected void Save() => _context.SaveChanges();

and the model is

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

Solution

  • I guess I need to use virtual and not the actual object for some reason.. The model looked fine but it seems to confused the update

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