EF(实体框架)“使用”语句和“尝试捕获”在彼此之内

时间:2013-08-04 05:26:47

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

使用此代码时有什么不同:

    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提交验证规则。 /

1 个答案:

答案 0 :(得分:1)

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

相关问题