c# - DbSet.Add & DbSet.Remove Versus using EntityState.Added & EntityState.Deleted -
in entity framework 6 there multiple way of adding / removing entities, example adding entities, can use:-
b.students.add(student); db.savechanges();
or
db.entry(student).state = entitystate.added; db.savechanges();
and when deleting object:-
db.entry(studenttodelete).state = entitystate.deleted; db.savechanges();
or
db.remove(studenttodelete) db.savechanges();
i did not find resources talks differences , , of online tutorials mention both approaches if same. have read reply on article link using dbset.add set status entity , related entities/collections added, while using entitystate.added
adds related entities/collections context leaves them unmodified, , same thing applies dbset.remove
& entitystate.deleted
so these differences correct ?
edit
as understand graph operation means both parent , child got deleted/added , if parent marked deletion or addition. did these 2 tests :-
using (var db = new testcontext()) { var = new department { departmentname = "shipping" }; var b = new employee { firstname = "bob", lastname = "dodds", department = }; 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 dept & employee. can adivce on please?
from lerman & miller's dbcontext book (p. 80):
calling
dbset.add
, settingstate
added
both achieve same thing.
which is:
if entity not tracked context, start being tracked context in
added
state. bothdbset.add
, settingstate
added
graph operations— meaning other entities not being tracked context , reachable root entity markedadded
. if entity (the root entity - addiditon) tracked context, movedadded
state.
note incorrectly answered in question refer to. book written ef 4.3 in mind, , doesn't mention breaking change since ef 4.1 when dbcontext
introduced.
setting entity's state deleted (either through dbset.remove()
or setting entry(entity).state
deleted
) not graph operation. affects entity's state, not entities in object graph.
the latter true entity state except added
.
an exception rule when cascaded delete configured, both in database , in ef model. in many-to-many association hidden junction table, cascaded delete default, junction records deleted when root entity marked delete (either setting state deleted
or removing dbset
).
for instance, let a
, b
have many-to-many association. junction table ab
in database, not in class model. if fetch a
database (without include()
-ing b
s) , delete it, a
deleted , al of ab
records, no b
s deleted.
when in one-to-many association cascaded delete configured 'many' entities deleted when '1' entity deleted. if a
, b
have one-to-many association, deleting a
delete b
s.
Comments
Post a Comment