I'm dropping database, creating it again and Seeding with data.
With this type of registry everything works fine
services.AddDbContext<Context>
(
options => options.UseSqlServer(Configuration["Database"]
);
But, when I add ServiceLifetime.Transient
then instantly it throws various exceptions like:
services.AddDbContext<Context>
(
options => options.UseSqlServer(Configuration["Database"], ServiceLifetime.Transient
);
SqlException: Violation of PRIMARY KEY constraint 'PK_myTable'. Cannot insert duplicate key in object 'dbo.myTable'. The duplicate key value is ( [guid] ). The statement has been terminated.
SqlException: Cannot insert explicit value for identity column in table 'myTable' when IDENTITY_INSERT is set to OFF.
What may be wrong?
public void Configure(IApplicationBuilder app, IHostingEnvironment env, Context context, SignInManager<User> sm, UserManager<User> um)
{
(...)
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
new Initializer(context, um).Initialize().Wait();
(...)
}
public class Initializer
{
private readonly UserManager<User> _userManager;
private readonly Context _ctx;
public Initializer(Context c, UserManager<User> um)
{
_ctx = c;
_userManager = um;
}
public async Task Initialize()
{
filling my objects with data
(No, I'm not setting value to Id anywhere)
_ctx.SaveChanges();
}
I bet that's because of async / .Wait()?