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;
}
}
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="[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();
}
}
Suppose, i want add new User with UserId=100. It will auto change UserId to 5.
How i can disable this modification of EF? 'UserId' must be primary key and it's type is int.
Configuring a primary key By convention, a property named Id or <type name>Id will be configured as the primary key of an entity. Owned entity types use different rules to define keys. You can configure a single property to be the primary key of an entity as follows: Data Annotations.
The Entity Framework Core Fluent API ValueGeneratedNever provides a way to specify that the value for the selected property should never be generated automtically by the database. This is useful if you want to circumvent the database's default behaviour.
The DatabaseGenerated attribute specifies how values are generated for a property by the database. The attribute takes a DatabaseGeneratedOption enumeration value, which can be one of three values: Computed. Identity. None.
1) Using Convention The Code First primary key convention is: Property with name " Id " or {class name} + " Id " will act as the primary key for that entity.
You have to change your attribute in User
class to:
Data annotations:
[System.ComponentModel.DataAnnotations.Schema.DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.None)]
public int UserId { get; set; }
or Fluent API:
modelBuilder.Entity<User>().Property(m => m.UserId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With