0

I want to add Users to my database Using DB Set but I am collecting only information about the Username and the password how can I add without UserID?

This is my constructor:

public class User
    {
        [Key]
        public int Id { get; set; }

        [Required]
        [MaxLength(30)]
        public string Username { get; set; }

        [Required]
        [MaxLength(30)]
        public string Password { get; set; }

        public List<Note> Notes { get; set; }

        public User(string username, string password)
        {
            this.Id =  1;
            this.Username = username;
            this.Password = password;
        }

And this is my Adding method:

                User user = new User(username, password);
                UserContext.Users.Add(user);
                UserContext.SaveChanges();

When I execute my code the database is still empty.

2
  • Can you share your entire user model please? Commented Mar 20, 2019 at 13:14
  • Yes, I edited the post Commented Mar 20, 2019 at 13:30

1 Answer 1

1

Try annotate the property like below to use the Auto-Increment https://www.w3schools.com/sql/sql_autoincrement.asp.

public class User
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required]
    [MaxLength(30)]
    public string Username { get; set; }

    [Required]
    [MaxLength(30)]
    public string Password { get; set; }

    public List<Note> Notes { get; set; }

    public User(string username, string password)
    {
        this.Username = username;
        this.Password = password;
    }
}

or use fluent api like this

modelBuilder.Entity<User>()
            .HasKey(p => new { p.Id });

modelBuilder.Entity<User>().Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.