【问题标题】:EF(entity framework) "using" statement and "try catch" withing each otherEF(实体框架)“using”语句和“try catch”相互配合
【发布时间】:2013-08-05 02:05:06
【问题描述】:

我使用这段代码有什么不同吗:

    public bool Insert(SomeEntity entity)
    {
        bool result = false;
        try
        {
            using (var db = new MyEntities())
            {
                db.AddToSomeEntity(entity);
                db.SaveChanges();
                result = true;
            }
        }
        catch (Exception e)
        {
            //
        }
        return result;
    }

还有这个:

    public bool Insert(SomeEntity entity)
    {
        bool result = false;
        using (var db = new MyEntities())
        {
            try
            {
                db.AddToSomeEntity (entity);
                db.SaveChanges();
                result = true;
            }
            catch (Exception e)
            {
                //
            }
        }
        return result;
    }

它会影响性能吗?

/添加此字符串是为了满足 SO 提交验证规则。/

【问题讨论】:

    标签: c# entity-framework try-catch using-statement


    【解决方案1】:

    我不认为它违反了任何规则,我建议您使用第二种方法,因为它更具体,并且您将在函数运行时将对象发送到垃圾收集完全执行,否则你可能会遇到一个异常,当你尝试使用不再可用的上下文时

    【讨论】:

    • 那么,如果我想知道有关异常的任何信息,我在第一种情况下找不到任何信息?
    • 你可以,但第二个会给你更多信息
    猜你喜欢
    • 1970-01-01
    • 2011-09-17
    • 2014-06-18
    • 2014-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-03
    • 1970-01-01
    相关资源
    最近更新 更多