In entity framework 6 there are multiple way of adding / removing entities, for example for adding entities, we can use:-
b.Students.Add(student);
db.SaveChanges();
OR
db.Entry(student).State = EntityState.Added;
db.SaveChanges();
and similarly when Deleting object:-
db.Entry(studentToDelete).State = EntityState.Deleted;
db.SaveChanges();
OR
db.Remove(StudentToDelete)
db.SaveChanges();
I did not find much resources that talks about the differences , and most of the online tutorials mention both approaches as if they are the same. but i have read a reply on an article link is that using dbset.Add set the status for the entity and all its related entities/collections to added, while using EntityState.Added
will adds also all the related entities/collections to the context but leaves them as unmodified, and same thing applies for dbset.Remove
& EntityState.Deleted
so are these differences correct ?
Edit
As i understand that graph operation means that both the parent and child got deleted/added , if the parent is marked for deletion or for addition. so i did these two tests :-
using (var db = new TestContext())
{
var a = new Department { DepartmentName = "Shipping" };
var b = new Employee { FirstName = "Bob", LastName = "Dodds", Department = a };
db.Entry(b).State = EntityState.Added;
db.SaveChanges();
}
using (var db = new TestContext())
{
var a2 = new Department { DepartmentName = "Production" };
var b2 = new Employee { FirstName = "Sarah", LastName = "Gomez", Department = a2 };
db.Employees.Add(b2);
db.SaveChanges();
}
where both have added the dept & the employee. so can you adivce on this please?