c# - Why does this bulk insert not work as expected? -
please see code snippet:
while ((line = rdr.readline()) != null) { .... departamento depto = db.departamento.firstordefault(d => d.depnombre.equals(departamento, stringcomparison.invariantcultureignorecase)); if (depto == null) { depto = new departamento(); depto.depnombre = departamento; depto.pais = pais; depto.depcreadoen = datetime.now; db.departamento.add(depto); } ... } db.savechanges();
as see, have loop inserting data table departamento
in database. instance, importing records excel sheet.
that "if" there insert records not in database, according name (depnombre
). when name exists, current object, that, not appear twice in database table.
as see, calling savechanges()
after loop, performance reasons.
the curious thing object not added collection, so, "depto" object returns null, adding record several times.
for example, there 1 record in database. using immediate window, can call db.departamento.count()
, 1 record found. after db.departamento.add
call, call same count()
method , 1 returned again. in case, firstordefault
method never return anything.
savechanges
call populates tables imported records.
any help, please?
var list=new list<departamento>(); /* excel */ while ((line = rdr.readline()) != null) { .... depto = new departamento(); depto.depnombre = departamento; depto.pais = pais; depto.depcreadoen = datetime.now; list.add(depto); } /* group */ var list2=list.groupby(x=>x.depnombre,(key,g)=>g.orderby(e=>e.depcreadoen).first()); /* list of depnombre exclude */ var baddepts=db.departmento .where(d=>list2.any(l2=>l2.depnombre==d.depnombre)) .select(d=>d.depnombre); /* exclude them */ var gooddepts=list2.where(l=>!baddepts.any(bd=>bd==l.depnombre)); /* add database */ db.departmento.addrange(gooddepts); /* save */ db.savechanges();
Comments
Post a Comment