c# - 如何使用 try-catch block 连接到 Entity Framework ?

标签 c# asp.net entity-framework-4

我是一名新的 ASP.NET 开发人员,这是我第一次使用 Linq-to-Entities 和 Entity Framework 。我现在的问题是关于使用连接到实体或数据库的最佳实践。我知道 try-catch block 非常昂贵。但是我应该在需要连接到数据库时使用它们吗?我问这个问题是因为我有大约 20 个实体,并且在我的数据访问层中,我拥有这些实体中每一个的所有 GetData() 方法。您能就此提出建议吗?

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

最佳答案

您绝对不想在这里捕获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.");
}

如果您需要有关如何实现自定义异常的指导,请参阅 answer .

关于c# - 如何使用 try-catch block 连接到 Entity Framework ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20908358/

相关文章:

asp.net - 剑道 UI MVC 4 : Form Validation inside a Window does not fire

c# - 使用 EntityFramework : Context per Presenter or long conversation pattern for Windows Forms Applications?

asp.net - Application_Start() 在 IIS7.5 托管的 MVC 5 应用程序中调用两次

c# - 在 Entity Framework 6.1 中添加存储过程的问题

c# - Entity Framework : does IQueryable or IEnumerable get all the results at the first place?

c# - GTK# 窗口图标不工作

c# - 来自数据库的数据未返回,但正常列表是

c# - 将类型库导入为 C# 代码的工具

c# - 为什么值类型不出现默认构造函数?

c# - 按类获取TinyMCE实例