Could anyone explain why there is a huge time execution time between the console application, which takes less than a second to execute, and the API takes minutes. Is it possible to improve ?
I am using .NET 7
Web app
var builder = WebApplication.CreateBuilder(args);
var cnn = new SqliteConnection("Data Source=EmployeeCacheStore;Mode=Memory;Cache=Shared");
cnn.Open();
builder.Services.AddDbContext<DataContext>(options => options.UseSqlite(cnn));
var app = builder.Build();
app.MapGet("/weatherforecast", (DataContext context1) =>
{
var time = Stopwatch.GetTimestamp();
context1.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
context1.ChangeTracker.AutoDetectChangesEnabled = false;
var list = Enumerable.Range(1, 8000).Select(x => new Record() { Id = x }).ToList();
context1.Record.AddRange(list);
context1.SaveChanges();
return $"Executed in: {Stopwatch.GetElapsedTime(time)}";
}).WithName("GetWeatherForecast");
app.Run();
Console:
var conn = new SqliteConnection("Data Source=EmployeeCacheStore;Mode=Memory;Cache=Shared");
conn.Open();
var options = new DbContextOptionsBuilder<DataContext>().UseSqlite(conn).Options;
using (var ctx = new DataContext(options))
{
var time = Stopwatch.GetTimestamp();
ctx.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
ctx.ChangeTracker.AutoDetectChangesEnabled = false;
var list = Enumerable.Range(1, 8000).Select(x => new Record() { Id = x }).ToList();
ctx.Records.AddRange(list);
ctx.SaveChanges();
Console.WriteLine("Executed in: {0}", Stopwatch.GetElapsedTime(time));
}
Context:
public class Record
{
public int Id { get; set; }
public string? Name { get; set; }
}
public class DataContext : DbContext
{
public DbSet<Record> Records { get; set; }
public DataContext(DbContextOptions options) : base(options)
{
Database.EnsureCreated();
}
}