Entity Framework automatically generates a primary key

I am 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 to add a new user with UserId = 100. It will automatically change the value of UserId to 5.

How can I disable this modification of EF? 'UserId' must be the primary key, and type - int.

+5
source share
1 answer

You must change your attribute in the User class to:

Data Annotations:

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

or Fluent API:

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

Source: https://habr.com/ru/post/1261695/


All Articles