2016-12-22 239 views
5

我新的實體框架。我有一個簡單的類:實體框架自動生成主鍵

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

我的初始化器類:

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(); 


    } 
} 

想,我要添加新的用戶用戶id = 100。它會自動更改用戶ID爲5

我如何可以禁用EF的這種修改?「用戶ID」必須是主鍵,它的類型是int。

+2

使用。 DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.None)]'。 –

+0

@M.Wiśnicki謝謝! – HungCung

回答

7

你必須User類更改屬性:

數據註釋:

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

或流利的API:在UserId` [System.ComponentModel.DataAnnotations

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