保存更改时实体框架错误

时间:2015-07-29 20:19:03

标签: entity-framework

我是Entity Framework的新手。目前我遇到了问题 - 当我尝试将新的User对象插入数据库时​​(使用方法RegisterNewUser),我一直收到错误:

  

违反PRIMARY KEY约束' PK__Users__3214EC07705D23AE'。无法在对象' dbo.Users'中插入重复键。重复键值为(0)。

这里有一些类似的问题,但这些答案都没有帮助我。

public void RegisterNewUser(String uName, String uPass, String fName, String lName, String email)
{
        User user = new User();
        user.Username = uName;
        user.Password = uPass;
        user.FirstName = fName;
        user.LastName = lName;
        user.Email = email;

        Time time = new Time();
        time.Time1 = DateTime.Now;

        user.Times.Add(time);

        ur.AddUser(user);
}

TimeUser个对象:

public partial class Time
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public int UserId { get; set; }
    public System.DateTime Time1 { get; set; }

    public virtual User User { get; set; }
}

public partial class User
{
    public User()
    {
        this.Times = new HashSet<Time>();
    }

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }

    public virtual ICollection<Time> Times { get; set; }
}

存储库文件

public class UsersRepository
{
    UsersDBContext userDBContext = new UsersDBContext();

    public List<User> GetUsers()
    {
        return userDBContext.Users.Include("Times").ToList();
    }

    public void AddUser(User user)
    {
        userDBContext.Users.Add(user);
        userDBContext.SaveChanges();
    }
}

和上下文

public partial class UsersDBContext : DbContext
{
    public UsersDBContext() : base("name=UsersDBContext")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }

    public virtual DbSet<Time> Times { get; set; }
    public virtual DbSet<User> Users { get; set; }
}

我不知道如何解决这个问题,所以任何建议都会非常有用

1 个答案:

答案 0 :(得分:0)

设置Id字段的值

将Id字段定义为自动增量