Entity Framework auto generate primary key

空扰寡人 提交于 2019-12-01 17:09:50

问题


I'm new to Entity Framework. I have a simple class:

 public class User
{
    [System.ComponentModel.DataAnnotations.Schema.DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string Email { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }

    //public UserList Users { get; set; }

    public User() { }
    public User(int userId, string email, string username)
    {
        UserId = userId;
        Email = email;
        UserName = username;
    }
}

And my Initializer class:

public class UserDataInitializer : DropCreateDatabaseAlways<UserDataContext>
{
    protected override void Seed(UserDataContext context)
    {
        var Users = new List<User> {

            new User() {UserId=1, Email="a1@gmail.com", UserName="a1", Password="123456"},
            new User() {UserId=2, Email="a2@gmail.com", UserName="a2", Password="123456"},
            new User() {UserId=3, Email="a3@gmail.com", UserName="a3", Password="123456"},
            new User() {UserId=4, Email="a4@gmail.com", UserName="a4", Password="123456"}}


        Users.ForEach(i => context.Users.Add(i));
        context.SaveChanges();


    }
}

Suppose, i want add new User with UserId=100. It will auto change UserId to 5.

How i can disable this modification of EF? 'UserId' must be primary key and it's type is int.


回答1:


You have to change your attribute in User class to:

Data annotations:

 [System.ComponentModel.DataAnnotations.Schema.DatabaseGenerat‌ed(System.ComponentM‌​odel.DataAnnotations‌​.Schema.DatabaseGeneratedOp‌​tion.None)]
 public int UserId { get; set; }

or Fluent API:

modelBuilder.Entity<User>().Property(m => m.UserId)
         .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);


来源:https://stackoverflow.com/questions/41278167/entity-framework-auto-generate-primary-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!