I had asp.net webapi project where below query was working fine
which is adding data into database and return newly added ID after _context.SaveChanges()
I'm using MYSQL database. It must have to work in MYSQL too :(
but when I migrate asp.net webapi code to asp.net CORE using EF CORE new record inserted into database successfully but after _context.SaveChanges() it returns 0 as newId instead new Id .
public partial class Student
{
public int Id { get; set; }
public string name { get; set; }
}
Student student = new Student()
student.name = "test";
_context.Add(student);
_context.SaveChanges()
int newID = student.Id ;
//got auto generated Id in asp.net webapi but in asp.net core project it is 0.
any clue ?
This doesn't repro for me with either EF Core 1.2 or 2.0.
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Threading.Tasks;
namespace ConsoleApp8
{
public partial class Student
{
public int Id { get; set; }
public string name { get; set; }
}
public class Db : DbContext
{
public DbSet<Student> Students { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Server=localhost;database=EfCoreTest;Integrated Security=true;MultipleActiveResultsets=false");
base.OnConfiguring(optionsBuilder);
}
}
class Program
{
static void Main(string[] args)
{
using (var db = new Db())
{
db.Database.EnsureDeleted();
db.Database.EnsureCreated();
Student student = new Student();
student.name = "test";
db.Add(student);
db.SaveChanges();
int newID = student.Id;
Console.WriteLine($"NewID {newID}");
}
Console.WriteLine("Hit any key to exit.");
Console.ReadKey();
}
}
}
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