Setting the state of an object graph (a collection of related entities) to Added
is different than setting a single entity as Added
(see this example).
In the example, we store planets and their moons:
Class model
public class Planet
{
public Planet()
{
Moons = new HashSet<Moon>();
}
public int ID { get; set; }
public string Name { get; set; }
public ICollection<Moon> Moons { get; set; }
}
public class Moon
{
public int ID { get; set; }
public int PlanetID { get; set; }
public string Name { get; set; }
}
Context
public class PlanetDb : DbContext
{
public property DbSet<Planet> Planets { get; set; }
}
We use an instance of this context to add planets and their moons:
var mars = new Planet { Name = "Mars" };
mars.Moons.Add(new Moon { Name = "Phobos" });
mars.Moons.Add(new Moon { Name = "Deimos" });
context.Planets.Add(mars);
Console.WriteLine(context.Entry(mars).State);
Console.WriteLine(context.Entry(mars.Moons.First()).State);
Output:
Added
Added
What we see here is that adding a Planet
also sets the state of a moon to Added
.
When setting an entity's state to Added
, all entities in its navigation properties (properties that "navigate" to other entities, like Planet.Moons
) are also marked as Added
, unless they already are attached to the context.