ef code first - Exception Handling in EF when Try To Delete Not Cascaded Entity -


assume there 2 entity:

public class category {     public string id { get; set; }     public string caption { get; set; }     public string description { get; set; }      public virtual ilist<product> products { get; set; } }  public class product {     public string id { get; set; }     public string categoryid { get; set; }     public string caption { get; set; }     public string description { get; set; }      public virtual category category { get; set; } } 

and cascade delete not allowed.

public class productmap : entitytypeconfiguration<product> {     public productmap()     {         // primary key         this.haskey(t => t.id);          // properties         this.property(t => t.caption)             .isrequired()             .hasmaxlength(50);          // table & column mappings         this.totable("products");         this.property(t => t.id).hascolumnname("id");         this.property(t => t.caption).hascolumnname("caption");          // relationships         this.hasrequired(t => t.category)             .withmany(t => t.products)             .hasforeignkey(d => d.categoryid)             .willcascadeondelete(false);     } } 

so when want delete category products related it, , dbupdateexception accurred. , in error message of exception write :

{"the delete statement conflicted reference constraint \"fk_dbo.products_dbo.categories_categoryid\". conflict occurred in database \"testdb\", table \"dbo.products\", column 'categoryid'.\r\nthe statement has been terminated."} 

there error code find out when accurred dbupdateexception related deleting dont cascade records? know sql server return error number 547 entity framework?

you can original sqlexception cause of entity framework specific exception.

that 1 contains sorts of useful information, number property containing sql server error code.

this should trick:

try {     tc.savechanges(); } catch (dbupdateexception ex) {     var sqlexception = ex.getbaseexception() sqlexception;      if (sqlexception != null)     {         var number = sqlexception.number;          if (number == 547)         {             console.writeline("must delete products before deleting category");         }     } } 

Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -