c# 4.0 - Error using foreign keys in entity framework -
i used foreign key
after clicked delete button
runs messagebox.show("error");
because foreign key
after clicked delete button
i not want insert table
again gives same error, delete
never can not insert or update table
again gives same error, delete
how problem solved
code delete
private void button1_click(object sender, eventargs e) { try { int del = convert.toint32(datagridview1.rows[datagridview1.currentrow.index].cells[0].value); t1 query = (from p in db.t1 p.id == del select p).firstordefault(); db.t1.remove(query); db.savechanges(); fill(); } catch { messagebox.show("error"); } }
code insert
try { db.t1.add(new t1() { names=textbox1.text }); db.savechanges(); //fill(); } catch { messagebox.show("error"); }
class code first
public partial class t1 { public t1() { this.t2 = new list<t2>(); } public int id { get; set; } public string names { get; set; } public virtual icollection<t2> t2 { get; set; } } public partial class t2 { public int id { get; set; } public nullable<int> fname { get; set; } public virtual t1 t1 { get; set; } }
sql setup http://sarbandi.ir/keramati/sqlpackage.exe
code example http://sarbandi.ir/keramati/examample.rar
i assume t1
object try delete has t2
objects in collection (as i used foreign key). first problem, delete, solved by
t1 t1 = db.t1.firstordefault(p => p.id == del); // same code, other syntax, or: db.t1.find(del); foreach(var t2 in t1.t2.tolist()) { db.t2.remove(t2); } db.t1.remove(t1); db.savechanges();
the second error caused fact have 1 dbcontext
instance (db
). second time try save, db
second effort commit delete failed before, that's still in there. (if you'd catch exception in stead of swallowing confirm this). delete , insert actions should each use own context instance new in using
construct:
using(var db = new mycontext()) { // stuff. }
side notes:
- try separate ui , data logic if meant more exercise.
- catch exceptions:
catch(exception exception)
in stead of showing messagebox.
(i must admit didn't @ links, hope bring in right track).
Comments
Post a Comment