Below...
On Sun, 2009-09-20 at 18:53 +0300, Andrus wrote:
> Web services methods contain lot of scalar queries like
>
> decimal? result;
> using (var db = new MyDataContext())
> result = (from entity in db.SomeTable
> where entity.Id=somevalue
> select d.DecimalColum).SingleOrDefault();
>
> To make code shorter those can also be re-written as
>
> decimal? result = (from entity in new MyDataContext().SomeTable
> where entity.Id=somevalue
> select d.DecimalColum).SingleOrDefault();
>
> In this case DataContext is not wrapped to using statement and maybe dispose
> is not called.
>
> Is it ok to use queries without using ?
.NET documents that DataContext.Dispose() does not normally need to be
called [0, 1]. DbLinq tries to remain semantically identical to .NET's
DataContext, and this is one such area. (You could also read the
source, and note that DbLinq's DataContext.Dispose() does nothing
useful, though that wouldn't protected against future changes,
while .NET's documentation will.)
> Can this query simplified more ?
In this case, skipping the 'using' is sufficient, but with other types
you might not be able to skip the 'using'. In these cases, you could
get a cleaner usage by using higher-order methods, e.g.:
public static R WithDatabase<R>(Func<MyDataContext, R> func)
{
using (var db = new MyDataContext())
return func (db);
}
// ...
decimal? result = WithDatabase(db =>
(from entity in db.SomeTable
where entity.Id = somevalue
select d.DecimalColumn).SingleOrDefault());
Or for something even more general:
public static R WithResource<T, R>(T resource, Func<T, R> f)
{
using (resource)
return f (resource);
}
// ...
decimal? result = WithResource(new MyDataContext(), db =>
(from entity in db.SomeTable
where entity.Id = somevalue
select d.DecimalColumn).SingleOrDefault());
- Jon
[0] http://msdn.microsoft.com/en-us/library/bb292288.aspx
[1] http://lee.hdgreetings.com/2008/06/linq-datacontex.html
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"DbLinq" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/dblinq?hl=en
-~----------~----~----~----~------~----~------~--~---