0

Possible Duplicate:
Should I use Linq To SQL directly in code behind or use some other approach?

I already asked a question previously Separation Of Linq Queries from code behind.

Maybe I could not get an answer I am looking for.So I am asking it once again.I use my linq to Sql queries in code behind directly. I use functions though.

My question is how should I seperate them from code behind?

What is a better approach. Should I use simple classes and perform my database operations(querying,insert,update,delete) there and then just call those functions from code behind.

Is it the approach that I should follow. If yes then should I go for a single class or should I create one class per page.

Can anyone just guide me how should I organize this.What are the approaches that you guys follow?

I am using ASP.NET Web Forms/C#.

A simple example will be a huge help.

Any suggestions are welcome.

Community
  • 1
  • 1
Priyank Patel
  • 6,898
  • 11
  • 58
  • 88

2 Answers2

1

You may choose a N-Tier approach, where you will have a Data Access Layer, Business Layer and Presentation Layer. Your Data Access layer will have the LINQ to SQL stuff, your Business layer should work as a bridge between your data access layer and presentation (UI) layer.

Look at the following article: Using LINQ to SQL in N-Tier Architectures

Habib
  • 219,104
  • 29
  • 407
  • 436
1

In some respects, LINQ queries shouldn't really be viewed as 'SQL' queries, even if they are then passed to a LINQ2SQL or an EF provider. LINQ expressions could arguably be viewed as flexible implementation of a query criteria pattern e.g. similar to Evan's specification pattern, specifying 'what' you want returned, ideally keeping SQL Specifics on 'how' to do this at a minimum.

That said, it can make a system difficult to test if you expose your DataContext or an IQueryable directly to your presentation tiers. Typically, you may wish to consider constraining your LINQ expressions to a dedicated 'data tier'.

Edit

There is a similar discussion here: http://social.msdn.microsoft.com/Forums/en-NZ/linqtosql/thread/2df752fd-6a1d-441b-b7c4-ecf1a7a00161

and specifically, there is a generic repository pattern for Linq2SQL here http://multitierlinqtosql.codeplex.com/

However, before implementing a heavily tiered architecture in Linq2SQL, you may reconsider replacing Linq2SQL with Entity Framework 4+. e.g. an issue with L2SQL is that the Entities are context-bound, meaning that you would need to map Simple data entities (POCOs) if you wanted to break the dependency on carrying your DataContexts around any layer which needs to use your entities. IMO Linq2SQL is best suited for small projects where you don't feel the need to abstract too much.

StuartLC
  • 104,537
  • 17
  • 209
  • 285