实体框架自动生成主键 [英] Entity Framework auto generate primary key

查看:112
本文介绍了实体框架自动生成主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是实体框架的新手。我有一个简单的类:

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

和我的Initializer类:

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


    }
}

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

Suppose, i want add new User with UserId=100. It will auto change UserId to 5.

如何禁用EF的这种修改?'UserId'必须是主键,其类型为

How i can disable this modification of EF? 'UserId' must be primary key and it's type is int.

推荐答案

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

You have to change your attribute in User class to:

数据注释:

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

或Fluent API:

or Fluent API:

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

这篇关于实体框架自动生成主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆