简体   繁体   中英

Entity Framework LINQ Insert

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM