c# - Use EF to delete a record by id, if id does not exist, an exception is thrown -
the code looks this:
try { student stu = new student() { id = id }; db.entry(stu).state = entitystate.deleted; int result = db.savechanges(); } catch (dataexception e) { }
the exception is:
store update, insert, or delete statement affected unexpected number of rows (0). entities may have been modified or deleted since entities loaded. see http://go.microsoft.com/fwlink/?linkid=472540 information on understanding , handling optimistic concurrency exceptions.
...but don't want exception, want number of affected rows, 0
.
try this
try{ var student= db.students.first(x => x.id== 1); db.students.deleteobject(student); db.savechanges(); } catch(exception ex) {return 0;}
Comments
Post a Comment