I am working on this project where I like to PreserveIds once inserted into the database. The id are auto incrementing and I return them once the data in inserted. I like to know if there is a better way using inheritance vs using a for each loop and checking if the value is 0?
class Program
{
static void Main(string[] args)
{
var States = new List<StatesModel>();
var CaliforniaCity = new List<CityModel>();
CaliforniaCity.Add(new CityModel() { Id = 2, Name = "Los Angeles" });
CaliforniaCity.Add(new CityModel() { Id = 3, Name = "Sacramento" });
CaliforniaCity.Add(new CityModel() { Id = 4, Name = "San Francisco" });
States.Add(new StatesModel() { Id = 1, Name = "California", CityModels = CaliforniaCity });
var PhiladelphiaCity = new List<CityModel>();
PhiladelphiaCity.Add(new CityModel() { Id = 5, Name = "Philadelphia" });
PhiladelphiaCity.Add(new CityModel() { Id = 6, Name = "Pittsburgh" });
PhiladelphiaCity.Add(new CityModel() { Id = 7, Name = "Harrisburg" });
States.Add(new StatesModel() { Id = 8, Name = "Pennsylvania", CityModels = PhiladelphiaCity });
var MichiganCity = new List<CityModel>();
MichiganCity.Add(new CityModel() { Id = 9, Name = "Detroit" });
MichiganCity.Add(new CityModel() { Id = 10, Name = "Lansing" });
MichiganCity.Add(new CityModel() { Id = 11, Name = "Grand Rapids" });
States.Add(new StatesModel() { Id = 12, Name = "Michigan", CityModels = MichiganCity });
///Insert Data in database
PreserveIds(States)
///Update data in database
foreach (var State in States)
{
Console.WriteLine(string.Format("{0}", State.Name));
Console.WriteLine(string.Format("{0} = {1}", State.Id ,State.OriginaId));
foreach (var city in State.CityModels)
{
Console.WriteLine(string.Format("{0}", city.Name));
Console.WriteLine(string.Format("{0} = {1}", city.Id, city.OriginaId));
}
}
}
public static void PreserveIds(IEnumerable<StatesModel> States)
{
if (States != null)
{
foreach (var State in States)
{
if (State.OriginaId == 0)
{
State.OriginaId = State.Id;
}
foreach (var city in State.CityModels)
{
if (city.OriginaId == 0)
{
city.OriginaId = city.Id;
}
}
}
}
}
}
Model
public class StatesModel
{
public int Id { get; set; }
public int OriginaId { get; set; }
public string Name { get; set; }
public List<CityModel> CityModels { get; set; }
public StatesModel()
{
CityModels = new List<CityModel>();
}
}
public class CityModel
{
public int Id { get; set; }
public int OriginaId { get; set; }
public string Name { get; set; }
}
OriginaId? Why do you need to store this ID? Why do you use the oldString.Format? Why don't you use "modern" initializers ( docs.microsoft.com/en-us/dotnet/csharp/programming-guide/… )? To me, this question is far too vague. \$\endgroup\$