What is the best way to handle linq to entity exceptions? Can I use try and catch block or is there better way?
A:
We used a try block to shield us from Save errors.
try{
using(Context context = new Context()){
Entity x = context.Entities.First();
x.ModifyMe = true;
context.SaveChanges();
}
}catch(UpdateException e){
//convert to friendly message
}
If you want to catch a lower exception there is also a OptimisticConcurrencyException
We also took it a bit further and just wrapped our SaveChanges in an extension method that was called protected save changes.
public static class Extension{
public static List<Error> ProtectedSaveChanges(this ObjectContext context){
try{
context.SaveChanges();
}catch(UpdateException e ){
//Convert to freindly and return
}
}
}
And believe it or not we decided to take it even further and have a special function that defined how to convert the exception method to a more user friendly error. If you want that one as well let me know and I can post.
As for an alternative way, i have seen people use exception shielding (EL), but i do not know if any built in Event Handlers for errors.
Nix
2010-07-01 18:18:07