I have following classes in my model:
public class Country
{
[Key]
public string Code { get; set; }
public string Name { get; set; }
public ICollection<State> States { get; set; }
}
public class State
{
public int ID { get; set; }
public string Code { get; set; }
public string Name { get; set; }
public Country Country { get; set; }
}
I know how to add a new Country and a new State using DbConext by coding like:
Country country = new Country() { Code = "USA", Name = "United States" };
State state = new State() { Code = "CA", Name = "California", Country = country };
db.Countries.Add(country);
db.States.Add(state);
db.SaveChanges();
// db is the instance of DbContext.
I was trying to do that in another way by creating only country and then add State to it's collection property:
Country country = new Country() { Code = "USA", Name = "United States" };
country.States.Add(new State() { Code = "CA", Name = "California" });
But I noticed that country.States
is null.
My questions are:
- How should I initialize
country.States
so I can add a new State to that collection. - Does doing it using the second method make any sense? (if it is feasible)