This blog article shows you how to insert values randomly from a List collection to SQL Server. I found a website that with the Cities and States of New Zealand. I have extracted some cities and states from the list and created a list of strings as the following code.
public static string GetRandom()
{
Random random = new Random();
List<string> list = new List<string> { “West Coast”, “Wellington”, “Lower Hutt”,
“Masterton”, “Porirua”, “Upper Hutt”, “Wellington”, “Tasman”, “Waikato” };
int index = random.Next(list.Count);
return (list[index]);
}
Then I Generate a Model for an Existing Database with the following database structure.
CREATE TABLE [dbo].[CountryState](
[gid] [uniqueidentifier] NOT NULL,
[StateName] [varchar](250) NULL,
CONSTRAINT [PK_CountryState] PRIMARY KEY CLUSTERED
(
[gid] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
Also: Generate Model from an Existing Database with specific tables using Entity Framework Core
The code below is to insert the random State to the database through Entity Framework.
public static void InsertDB(string state)
{
PocContext context = new PocContext();
CountryState country = new CountryState();
country.StateName = state;
context.Add(country);
context.SaveChanges();
}
Finally, you have a main function to call the GetRandom and InsertDB function.
static void Main(string[] args)
{
string state = “”;
// Scaffold-DbContext “Server=localhost;Database=poc;Trusted_Connection=True;TrustServerCertificate=true” t.EntityFrameworkCore.SqlServer -OutputDir Models -t CountryState -f
state = InsertRandom();
InsertDB(state);
}

Source code download: https://github.com/chanmmn/database/tree/main/ConAppRandomState/?WT.mc_id=DP-MVP-36769
Reference: https://www.tutorialspoint.com/how-to-select-a-random-element-from-a-chash-list
https://www.britannica.com/topic/list-of-cities-and-towns-in-New-Zealand-2041679
Pingback: Update using Subquery SQL | Chanmingman's Blog