我是ASP.NET的新开发人员,这是我第一次使用Linq-to-Entities和Entity Framework。我现在的问题是关于使用最佳实践来连接实体或数据库。我知道try-catch块非常昂贵。但是,当我需要连接到数据库时,是否应该使用它们?我问这个问题是因为我有大约20个实体,并且在我的数据访问层中,对于每个这些实体我都有所有的GetData()方法。您能对此提出建议吗?
C#代码:
public static IEnumerablegetData() { List itemsList = new List (); try { using (ItemsDBEntities context = new ItemsDBEntities()) { itemsList = (from item in context.Items select new Items() { ID = item.ID, Code = item.Code, Name = item.Name, StatusID = item.StatusID }).ToList(); } } catch (EntityException ex) { //something wrong about entity } catch (Exception ex) { //Don't know what happend... } return itemsList; }
James.. 6
你绝对不希望赶上Exception
这里,因为你可能会掩盖其他的(可能更大)的问题与您的代码。
通常,只有打算以某种方式处理异常时,才应捕获异常。例如,在您的方案中,如果连接失败,则可能要显示UI消息。最好的方法是让异常冒泡到您实际要在其中处理的层。
为了避免各层之间的耦合,一种好的方法是在DAL中捕获特定于存储的异常,并引发一个特定于应用程序的异常,然后可以在上层进行处理,例如
DAL
public static IEnumerablegetData() { List itemsList = new List (); try { using (ItemsDBEntities context = new ItemsDBEntities()) { itemsList = (from item in context.Items select new Items() { ID = item.ID, Code = item.Code, Name = item.Name, StatusID = item.StatusID }).ToList(); } } catch (EntityException ex) { throw new ConnectionFailedException(ex); } return itemsList; }
用户界面
try { var items = Repo.getData(); ... } catch (ConnectionFailedException) { MessageBox.Show("There was a problem accessing the database, please try again."); }
如果您需要有关如何实现自定义异常的指南,请参见此答案。
你绝对不希望赶上Exception
这里,因为你可能会掩盖其他的(可能更大)的问题与您的代码。
通常,只有打算以某种方式处理异常时,才应捕获异常。例如,在您的方案中,如果连接失败,则可能要显示UI消息。最好的方法是让异常冒泡到您实际要在其中处理的层。
为了避免各层之间的耦合,一种好的方法是在DAL中捕获特定于存储的异常,并引发一个特定于应用程序的异常,然后可以在上层进行处理,例如
DAL
public static IEnumerable<Items> getData() { List<Items> itemsList = new List<Items>(); try { using (ItemsDBEntities context = new ItemsDBEntities()) { itemsList = (from item in context.Items select new Items() { ID = item.ID, Code = item.Code, Name = item.Name, StatusID = item.StatusID }).ToList(); } } catch (EntityException ex) { throw new ConnectionFailedException(ex); } return itemsList; }
用户界面
try { var items = Repo.getData(); ... } catch (ConnectionFailedException) { MessageBox.Show("There was a problem accessing the database, please try again."); }
如果您需要有关如何实现自定义异常的指南,请参见此答案。