Insert to SqlLite database using EF always return 1 for Id

I have a simple contact app that uses sqllite as database. I use EF code first to design it’s database. When I save the data, It’s Id produces in database as expected (Auto Increment), but the SaveChanges method always return 1 for Id.

How can I get the latest table Id?

DbContext :

public class ApplicationDbContext : DbContext
    protected override void OnConfiguring(DbContextOptionsBuilder options)
        string dbPath = DbPathGenerator.GetDbPath();

        options.UseSqlite($"Data Source={dbPath}/LiteContactsDb.db");

    public DbSet<Person> Persons { get; set; }
    public DbSet<Address> Addresses { get; set; }
    public DbSet<Phone> Phones { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
            .WithOne(a => a.Person)
            .HasForeignKey(a => a.PersonId);

            .WithOne(a => a.Person)
            .HasForeignKey(a => a.PersonId);


Save Method :

    public bool SaveContact(PersonViewModel personViewModel, PhoneViewModel phoneViewModel, AddressViewModel addressViewModel)
        bool result = false;

            Person person = new Person();

            person.FirstName = personViewModel.FirstName;
            person.LastName = personViewModel.LastName;
            person.Email = personViewModel.Email;

            var personId = _context.SaveChanges();

            Phone phone = new Phone();

            phone.PersonId = personId;
            phone.PhoneTitle = phoneViewModel.PhoneTitle;
            phone.PhoneNumber = phoneViewModel.PhoneNumber;

            Address address = new Address();

            address.PersonId = personId;
            address.AddressTitle = addressViewModel.AddressTitle;
            address.AddressString = addressViewModel.AddressString;
            address.PostalCode = addressViewModel.PostalCode;



            result = true;
        catch (Exception ex)
            result = false;

        return result;

_context.SaveChanges(); always returns 1.


>Solution :

The return value of SaveChanges is not the id of the newly created record, but the number of changes. So if you insert a single item, the return value will always be 1.

If you want to access the id of the newly inserted object, check out the id-property of the object. It is updated after the insert.

Leave a Reply