Linq To Sql DataContext scope

M

Marc Vangrieken

Hi,

I read on msdn that "In general, a DataContext instance is designed to
last for one "unit of work" however your application defines that
term. A DataContext is lightweight and is not expensive to create. A
typical LINQ to SQL application creates DataContext instances at
method scope or as a member of short-lived classes that represent a
logical set of related database operations."

Is there any particular reason for this? What's the penalty (if there
is one) for making it long-lived? Will, for instance, the identity map
inside take to much memory?

Thanks, I'm just trying to understand...
 
N

Nicholas Paldino [.NET/C# MVP]

Marc,

Well, too much memory depends on what your app is doing, how much memory
is available to it, etc, etc.

But generally, yes, the identity map is probably going to become
bloated, to say the least, and the potential for confusion/mixup is much,
much greater if you hold it around.

Also, if you have transactions wrapping your operations, then I can see
that possibly being an issue, as if you held the DataContext past a
transaction, and the transaction aborted, you could be out of sync with the
underlying database in a big way.
 
M

Marc Vangrieken

Marc,

Well, too much memory depends on what your app is doing, how much memory
is available to it, etc, etc.

But generally, yes, the identity map is probably going to become
bloated, to say the least, and the potential for confusion/mixup is much,
much greater if you hold it around.

Also, if you have transactions wrapping your operations, then I can see
that possibly being an issue, as if you held the DataContext past a
transaction, and the transaction aborted, you could be out of sync with the
underlying database in a big way.

--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)


I read on msdn that "In general, a DataContext instance is designed to
last for one "unit of work" however your application defines that
term. A DataContext is lightweight and is not expensive to create. A
typical LINQ to SQL application creates DataContext instances at
method scope or as a member of short-lived classes that represent a
logical set of related database operations."
Is there any particular reason for this? What's the penalty (if there
is one) for making it long-lived? Will, for instance, the identity map
inside take to much memory?
Thanks, I'm just trying to understand...

Thanks for the info Nicholas! I'm going to add this as a best practice
to my LINQ to SQL presentations...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top