Are there any side effects of returning from inside a using() statement?

前端 未结 5 1330
一向
一向 2021-01-31 07:02

Returning a method value from inside a using statement that gets a DataContext seems to always work fine, like this:

public sta         


        
5条回答
  •  执笔经年
    2021-01-31 07:14

    Yes, there can be a side effect. For example, if you use the same technique in ASP.NET MVC Action method, you will get the following error: "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection"

    public ActionResult GetMostRecentTransaction(int singleId)
    {
        using (var db = new DataClasses1DataContext())
        {
            var transaction = (from t in db.Transactions
                                  orderby t.WhenCreated descending
                                  where t.Id == singleId
                                  select t).SingleOrDefault();
            return PartialView("_transactionPartial", transaction);
        }
    }
    

提交回复
热议问题