我是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。
答案 0 :(得分:8)
您必须将User
课程中的属性更改为:
数据注释:
[System.ComponentModel.DataAnnotations.Schema.DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.None)]
public int UserId { get; set; }
或Fluent API:
modelBuilder.Entity<User>().Property(m => m.UserId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);