简体   繁体   中英

EF(entity framework) "using" statement and "try catch" withing each other

Is there any difference between these ways of using/try-catch blocks?

First :

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

Second :

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

Does it affect performance?

This string was added in order to satisfy SO submit validation rule.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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