实体框架自动生成主键

时间:2016-12-22 07:49:42

标签: c# entity-framework

我是Entity Framework的新手。我有一个简单的课程:

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


    }
}

假设,我想添加UserId = 100的新用户。它会自动将UserId更改为5。

如何禁用对EF的修改?&#39; UserId&#39;必须是主键,它的类型是int。

1 个答案:

答案 0 :(得分:8)

您必须将User课程中的属性更改为:

数据注释:

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

或Fluent API:

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