c# - EF 6: Removing entities results in empty objects -
i have confusing situation occurring on database. reasons can't determine, whenever remove item dbset held dbcontext (called datarepository
), 3 more "empty" items of same type added.
here's code teacher
entity (it inherit user
, , use tpt inheritance handle that).
public class teacher : user { public string title { get; set; } public string email { get; set; } public virtual department department { get; set; } public virtual list<class> classes { get; set; } public virtual list<booking> bookings { get; set; } public teacher() { department = new department(); internalbookings = new list<booking>(); classes = new list<class>(); access = accessmode.teacher; title = string.empty; email = string.empty; } }
similarly, department
entity.
public class department { public string name { get; set; } public virtual list<teacher> teachers { get; set; } public virtual list<room> rooms { get; set; } public department() { teachers = new list<teacher>(); rooms = new list<room>(); name = string.empty; } }
edit: , relevant parts of datarepository
code:
public class datarepository : dbcontext { public virtual dbset<booking> bookings { get; set; } public virtual dbset<department> departments { get; set; } public virtual dbset<class> classes { get; set; } public datarepository() : base(@"data source=(localdb)\mssqllocaldb;attachdbfilename=" + path + ";database=data;integrated security=true;multipleactiveresultsets=true;app=entityframework") { database.setinitializer(new dropcreatedatabasealways<datarepository>()); } }
then, in testing code, have:
using (datarepository repo = new datarepository()) { repo.bookings.remove(repo.bookings.single(b => b.id == 1)); repo.teachers.remove(repo.teachers.single(t => t.firstname == "r....")); repo.classes.remove(repo.classes.single(c => c.owner == repo.teachers.firstordefault(t => t.firstname == "r...."))); repo.savechanges(); }
this removes 1 of booking
entities in db, associated teacher
, class
(as result, there no orphaned entities in db).
the problem after running code, dbset of department
s in dbcontext has three extra, empty items. can put breakpoint in constructor of department
, see new objects being created. call stack can infer it's being created iterator, surely wouldn't add database?
another strange effect using, repo.bookings.remove(repo.bookings.tolist().single(b => b.id == 1))
, end 7 new items instead.
i think i'm missing important here, appreciated.
solution remove initialisations of entries in constructors of other entries - list initialisations ok, not entries themselves.
your empty constructor teacher
creates new department
no name (hence empty items). ef notices "change" , saves departments table.
ef requires parameterless constructor create objects wants return queries, in case creating objects causes changes. more objects creates internally while performing queries, more empty items in table.
Comments
Post a Comment