Reputation: 815
I'm trying to use LINQ to insert an object in my database. My primary key is auto increment. Do I need to increment the id in my code or Entity Framework can do it?
I have my dbContext:
TravelAgencyEntities db = new TravelAgencyEntities();
I'm trying to insert a User object:
User newUser = new User();
newUser.FirstName = firstName.Text.ToString();
newUser.LastName = lastName.Text.ToString();
newUser.Email = email.Text.ToString();
newUser.Password = password.Text.ToString();
db.Users.Add(newUser);
db.SaveChanges();
It returns an exception:
{"An error occurred while updating the entries. See the inner exception for details."}
I think that error is because I do not set the id in my object, but it should be auto increment. Does anyone know the problem?
The INNER ERROR:
Cannot insert explicit value for identity column in table 'User' when IDENTITY_INSERT is set to OFF
Upvotes: 0
Views: 1230
Reputation: 4776
If you use code first, probably have set following code in DbContext OnModelCreating.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<User>()
.Property(a => a.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
}
Or set as attribute like following
public class User
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
.....
}
you must change None to Identity. Identity option is default for key.
Upvotes: 1