5
Tôi mới làm quen với Khung thực thể. Tôi có một lớp đơn giản:Khung thực thể tự động tạo khóa chính
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;
}
}
Và lớp Initializer tôi:
public class UserDataInitializer : DropCreateDatabaseAlways<UserDataContext>
{
protected override void Seed(UserDataContext context)
{
var Users = new List<User> {
new User() {UserId=1, Email="[email protected]", UserName="a1", Password="123456"},
new User() {UserId=2, Email="[email protected]", UserName="a2", Password="123456"},
new User() {UserId=3, Email="[email protected]", UserName="a3", Password="123456"},
new User() {UserId=4, Email="[email protected]", UserName="a4", Password="123456"}}
Users.ForEach(i => context.Users.Add(i));
context.SaveChanges();
}
}
Giả sử, tôi muốn thêm tài khoản mới với UserId = 100. Nó sẽ tự động thay đổi UserId thành 5.
Làm thế nào tôi có thể vô hiệu hóa sửa đổi này của EF? 'UserId' phải là khóa chính và loại đó là int.
Sử dụng trên UserId' [System.ComponentModel.DataAnnotations. DatabaseGenerated (System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.None)] '. –
@ M.Wiśnicki Cảm ơn! – HungCung