使用Identity class

时间:2018-04-20 17:17:03

标签: asp.net-core asp.net-identity entity-framework-core

我有一个测验sql架构,我也在使用ASP.NET Identity。当我尝试将用户的答案插入UserAnswer表时,我收到以下错误。好像它试图插入到User表中,但我不想这样做?

  

违反PRIMARY KEY约束'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; }
}

1 个答案:

答案 0 :(得分:0)

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

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