I'm new to Entityframework in my practice app I'm trying to initialize my newly created database with some sample data and using SaveChangesAsync() but its giving internal server error. When I migrated my DbContext there was no problem and the database created successfully.
EDITED:
after debugging I found SqlException: Cannot insert explicit value for identity column in table 'Packages' when IDENTITY_INSERT is set to OFF
what should I do?
DbInitializer
public class DbContextInitializer
{
private AppDbContext _context;
private Data data = new Data();
public DbContextInitializer(AppDbContext context)
{
_context = context;
}
public async Task SeedData()
{
if (!_context.Packages.Any())
{
var pack1 = data.get(1);
_context.Packages.Add(pack1);
var pack2 = data.get(2);
_context.Packages.Add(pack2);
var pack3 = data.get(3);
_context.Packages.Add(pack3);
await _context.SaveChangesAsync();
}
}
}
DbContext
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}
public DbSet<TableModel> Packages { get; set; }
}
Configure in Startup.cs
public void Configure(IApplicationBuilder app,
IHostingEnvironment env,
DbContextInitializer seed)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=App}/{action=Index}/{id?}");
});
seed.SeedData().Wait();
}
ConfigureServices in Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AppDbContext>(options => options.UseSqlServer(_configurationroot.GetConnectionString("ConString")));
services.AddMvc();
services.AddTransient<ITableData, MockTableData>();
services.AddTransient<DbContextInitializer>();
}