处理实体框架4中的异常 [英] Handle exceptions in entity framework 4

查看:62
本文介绍了处理实体框架4中的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一种使用实体框架LINQ区分SQL异常的方法,例如,当我从DbUpdateException获得的所有信息都是大量嵌套的内部异常和无用的长错误消息时,如何区分前面的关键约束违反或唯一约束违反?是否有任何较低级别的异常可以执行 Catch FKException之类的操作?捕获 uniqueException或类似的东西。

I need a way to distinguish between SQL exceptions using entity framework LINQ, for example how to distinguish foreing key constraint violation, or unique constraint violation when all i get from the DbUpdateException is a ton of nested inner exceptions and useless long error messages? Are there any lower level exceptions where i can do something like "Catch FKException"; catch "uniqueException" or something like that.

推荐答案

使用sql错误代码...

Using sql error codes...

catch (DbUpdateException ex)
                    {
                        var sqlex = ex.InnerException.InnerException as SqlException;

                        if (sqlex != null)
                        {
                            switch (sqlex.Number)
                            {
                                case 547: throw new ExNoExisteUsuario("No existe usuario destino."); //FK exception
                                case 2627:
                                case 2601:
                                    throw new ExYaExisteConexion("Ya existe la conexion."); //primary key exception

                                default: throw sqlex; //otra excepcion que no controlo.


                            }
                        }

                        throw ex;
                    }

这篇关于处理实体框架4中的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆