NOTE: I'm experimenting with EntityFrameworkCore 5.x and .NET 6.0 inside of VS2022 Preview.
I've got my code set up to loop and add a first name and a last name to a user object which updates a user table in SQLServer. If I have the loop, it updates the database but short circuits the loop. Removing the loop adds a single user to the database and exits the program as expected.
I understand it's best practice to do all the adds and then update, but what is the technical reason for the short circuit?
The code:
using EFGetStarted;
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
EFGetStartedEntryPoint.Execute();
Console.ReadKey();
}
}
}
using EFGetStarted.Controllers;
using EFGetStarted.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EFGetStarted
{
public static class EFGetStartedEntryPoint
{
private static string connstring = @"Server=myServer;Database=EFGetStarted;Trusted_Connection=true";
public async static void Execute()
{
var contextOptions = new DbContextOptionsBuilder<EFGetStartedDbContext>()
.UseSqlServer(connstring)
.Options;
using (var db = new EFGetStartedDbContext(contextOptions))
{
int counter = 1;
while (true)
{
User user = new User() { FirstName = "John", LastName = "Doe" + counter.ToString() };
await db.AddAsync<User>(user);
await db.SaveChangesAsync();
Console.WriteLine("SaveChanges Completed Successfully");
counter++;
Console.ReadKey();
}
}
}
}
}
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EFGetStarted.Models
{
public class User
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Int64 UserID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EFGetStarted.Models
{
public class EFGetStartedDbContext : DbContext
{
public DbSet<User> tbUsers { get; set; }
public EFGetStartedDbContext(DbContextOptions<EFGetStartedDbContext> options)
: base(options)
{
}
}
}