EF - Retrieve Id of Inserted Entity

CSharp · Console

/Program.cs

// @nuget: EntityFramework

using System;
using System.Data.Entity;
using System.Linq;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;

public class Program
{
	public static void Main()
	{
		using (var context = new EntityContext())
		{
			var customer = new Customer()
			{
				Name = "John"
			};

    		context.Customers.Add(customer);
			
			context.SaveChanges();
				
			int id = customer.CustomerID;
			Console.WriteLine(id);
		}
	}
	

	public class EntityContext : DbContext
	{
		public EntityContext() : base(FiddleHelper.GetConnectionStringSqlServer())
		{

		}
		
		public DbSet<Customer> Customers { get; set; }
	}
	
	
	public class Customer
	{
		public int CustomerID { get; set; }
		public string Name { get; set; }
	}
}
;