简体   繁体   English

如何使用try-catch块连接到Entity Framework?

[英]How to use try-catch block to connect to the Entity Framework?

I am a new ASP.NET developer and this is my first time to use Linq-to-Entities and Entity Framework. 我是一名新的ASP.NET开发人员,这是我第一次使用Linq-to-Entities和Entity Framework。 My problem now is about using the best practice of connecting to the Entities or Database. 我现在的问题是使用连接到实体或数据库的最佳实践。 I know that try-catch block is very expensive. 我知道try-catch块非常昂贵。 But should I use them whenever I need to connect to the database? 但是,每当我需要连接数据库时,我应该使用它们吗? I am asking this question because I have around 20 entities and in my Data Access Layer, I have all the GetData() methods for each one of these entities. 我问这个问题,因为我有大约20个实体,在我的数据访问层中,我为这些实体中的每一个都拥有所有GetData()方法。 Could you please advise on this? 你能就此提出建议吗?

C# code: C#代码:

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)
    {
        //something wrong about entity
    }
    catch (Exception ex)
    {
        //Don't know what happend... 
    }
    return itemsList;
}

You definitely don't want to catch Exception here because you could mask other (possibly bigger) problems with your code. 你肯定希望赶上Exception这里,因为你可能会掩盖其他的(可能更大)的问题与您的代码。

Generally, you should only catch exceptions if you intend on handling them in some way. 通常,如果您打算以某种方式处理异常,则应该只捕获异常。 For example, in your scenario you might want to display a UI message if the connection fails. 例如,在您的方案中,如果连接失败,您可能希望显示UI消息。 The best approach for this is to let the exception bubble up to the layer in which you actually want to handle it in. 最好的方法是让异常气泡到你真正想要处理它的层。

To avoid coupling between your layers a good approach is to catch the storage-specific exception in the DAL and raise a more application-specific exception which you can then handle in the upper layers eg 为了避免层之间的耦合,一个好的方法是捕获DAL中特定于存储的异常,并引发更多特定于应用程序的异常,然后您可以在上层处理,例如

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;
}

UI UI

try
{
    var items = Repo.getData();
    ...
}
catch (ConnectionFailedException)
{
    MessageBox.Show("There was a problem accessing the database, please try again.");
}

If you need guidance on how to go about implementing a custom exception, see this answer . 如果您需要有关如何实现自定义异常的指导,请参阅此答案

try-catch block is very expensive. try-catch块非常昂贵。

Try is cheap, catch is cheap, throw is expensive. 尝试便宜,抓住便宜,扔很贵。 So, if code execution follows normal path (does not produce exceptions), try-catch's are no problem. 因此,如果代码执行遵循正常路径(不产生异常),则try-catch是没有问题的。 (BTW, expensive throw is one reason why you should avoid exception-based logical flows in your code) Even if you avoid try-catch block, throwing is still expensive. (BTW,昂贵的抛出是你应该避免代码中基于异常的逻辑流的一个原因)即使你避免使用try-catch块,抛出仍然很昂贵。

should I use them whenever I need to connect to the database? 我需要连接数据库时应该使用它们吗?

This comes down to your judgement call. 这取决于你的判断。 Generally, it is a bad idea to have naked throws between layers of your app. 通常,在应用层之间进行裸投是个坏主意。 It is equally bad idea to have multiple catches within a single block of your app. 在应用程序的单个块中有多个捕获也同样糟糕。

I'd say you definitely want to catch Exception on top level of your DAL: client should not care about your internal problems (DB connections, timeouts, bad logins, etc.). 我想你肯定想要在你的DAL的最高级别上捕获异常:客户端不应该关心你的内部问题(数据库连接,超时,糟糕的登录等)。

And here I have to basically just quote previous answer: 在这里我基本上只是引用以前的答案:

to avoid coupling between your layers... raise a custom, application specific, exception which you can then handle in the upper layers 避免你的图层之间的耦合......提出一个自定义的,特定于应用程序的异常,然后你可以在上层处理它

Two good ideas for your catch 's is to (1) log exception (so DAL's side knows about it afterwards), (2) have unit tests in place (pre-execute SQL to write known data into DB, then invoke GetData()) so that you can detect general problems prior releasing DAL for client's use catch的两个好主意是(1)记录异常(因此DAL的一方事后知道它),(2)有单元测试(预执行SQL将已知数据写入DB,然后调用GetData()) )这样您就可以在释放DAL之前检测一般问题,以供客户使用

Do not catch an exception unless you intend to do something with it. 除非你打算用它做什么,否则不要捕捉异常。 For example maybe you want to retry connecting to the db x number of times before allowing the exception to bubble up. 例如,您可能希望在允许异常冒泡之前重试连接到db x次数。 I would suggest not bothering wrapping you code in a try catch unless you are going to do something special. 除非你打算做一些特别的事情,否则我建议不要在try catch中包装你的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM