这是启动类从现有数据库中播种数据的方法。如果我将indentity_insert设置为ON,我不明白为什么它会给我一个例外:
public void Configure(IApplicationBuilder app,IHostingEnvironment env,ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("记录&#34)); loggerFactory.AddDebug();
app.UseApplicationInsightsRequestTelemetry();
//Seed data
using (var context = app.ApplicationServices.GetService<ApplicationDbContext>())
{
if (env.IsDevelopment())
{
context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT dbo.Customers ON");// i turn on
context.SaveChanges();
//seed code here
string path = "C:\\Users\\Reynaldo\\Desktop\\playin\\CustomerT.csv";
using (TextReader fileReader = System.IO.File.OpenText(path))
{
Mapper.Initialize(cfg =>
{
cfg.CreateMap<CustomerViewModel, Customer>()
.ForMember(dto => dto.Name, conf => conf.MapFrom(ol => ol.FirstName))
.ForMember(dto => dto.Id, conf => conf.MapFrom(ol => ol.CustomerId))
.ForMember(dto=>dto.PlanType,conf=>conf.Ignore())
.ForMember(dto => dto.SalePayments, conf => conf.Ignore()); ;
cfg.CreateMap<string, double>().ConvertUsing(Convert.ToDouble);
cfg.CreateMap<string, DateTime>().ConvertUsing(new DateTimeTypeConverter());
});
var reader = new CsvReader(fileReader);
reader.Configuration.RegisterClassMap<CustomerViewModelMap>();
var allvalues = reader.GetRecords<CustomerViewModel>();
foreach (var item in allvalues)
{
var x = Mapper.Map<Customer>(item);
context.Customers.Add(x);
break;
}
}
context.SaveChanges();//here is when the exception throws.
context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT dbo.Customers OFF");
context.SaveChanges();
}
}
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseApplicationInsightsExceptionTelemetry();
app.UseStaticFiles();
app.UseIdentity();
// Add external authentication middleware below. To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}