问题
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.DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.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