views:

69

answers:

1

Hey,

I was wondering what the "correct"-way is when using a Linq to Sql-model in Visual Studio. Should I create a new model for each of my components, say Blog, Users, News and so on and have all different xxxDataContext's with tables and SPROCs added in each of these.

Or should I create one MyDbDataContext and always work against that?

What's the pro's/con's? My gut tells me to divide it up in smaller context's, but it also feels like that could bring problems as the project expands?

What's the deal? Help me Stackoverflow :)

+1  A: 

There will always be overhead when creating the data context as the model needs to be built. Depending on the number of tables in your database this might not be much of a big deal though. If it's only 10 tables or so, the overhead will not be much more than that for a context with say 1 table (sorry, I don't have actual stress testing to show the overhead, but, hey, maybe that gives me something to blog on this weekend).. When looking at large databases the overhead might be a enough to consider using seperate contexts.

The main advantage I would see with using a single data context is that you gain the ability to use JOINs in your LINQ query and that will be translated to T-SQL. Where as if you do the join after the arrays of objects are pulled, the performance might be a bit slower. Additionally, keeping track of multiple data contexts might be confusing and good naming conventions would be needed. So building your own data model w/ business logic which encapsulates the contexts would be a bit harder. I've done this and it's not fun :)

However, if you still feel you want to go that route, then I would recommend putting similar tables (that you might need to join) in the same context. Also, there are some tuts online that recommend using a shared MappingSource when using multiple contexts that use the same source. Information on this can be found here: http://www.albahari.com/nutshell/speedinguplinqtosql.aspx

Sorry, I know that's not really a black and white answer, but hopefully it helps :)

Addition:

Just wanted to add that I did a small test and ran 20,000 SELECT statements against a small sized table using 2 different data contexts: DataClasses1DataContext contained mappings to all tables in the db (4 total) DataClasses2DataContext contained a single mapping for just the one table

Results:

Time to execute 20000 SELECTs using DataClasses1DataContext: 00:00:10.4843750

Time to execute 20000 SELECTs using DataClasses2DataContext: 00:00:10.4218750

As you can see, it's not much of a difference.

regex
Thanks for that informative post, gave me something to think about. Going to read the link as soon as I get to the office.
blueblood
no problem. I've always thought about that same question as well. You gave me some motivation do run some tests, so I learned a bit too.
regex
Cool :) May I ask for the URL to your blog?
blueblood