EF在SQL Server中添加不带用户ID的用户

时间:2019-03-20 13:09:42

标签: c# sql-server entity-framework

我想使用数据库集将用户添加到数据库中,但是我仅收集有关用户名和密码的信息,如何在没有用户ID的情况下添加?

这是我的构造函数:

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

这是我的添加方法:

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

执行代码时,数据库仍然为空。

1 个答案:

答案 0 :(得分:1)

尝试如下注释属性,以使用自动增量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;
    }
}

或像这样使用流利的api

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

modelBuilder.Entity<User>().Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);