简体   繁体   中英

Adding values to database with an auto-increment Id

I wonder how I can get a different Id for every weight input I make.

The console application worked fine the first time, but it doesn't add any more rows in the table.

My console code:

class Program
{
    int weightInput = 0;
    int calorieInput = 0;

    private void addWeight()
    {
        Weight weight = new Weight();

        weight.date = DateTime.Today;
        weight.kg = weightInput;

        using (weighttrackerEntities context = new weighttrackerEntities())
        {
            context.Weights.Add(weight);
            context.SaveChanges();
        }
    } 
}

My Weight entity:

public partial class Weight
{
    public int Id { get; set; }
    public int kg { get; set; }
    public System.DateTime date { get; set; }
}

You should mark the ID for auto increment using the model builder

modelBuilder.Entity<Foo>()
            .Property(f => f.Id)
            .ValueGeneratedOnAdd();

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