Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to SQL in 3-layer architecture

Tags:

linq-to-sql

I currently use the 3-layer architecutre (DAL, BLL, Presentation Layer).

I am wondering how I can implement the 3 layers architecture using LINQ to SQL. I don't know whether LINQ should be in DAL or BLL. LiNQ seems the fusion of both DAL and BLL.

Does anyone implement LINQ in 3-layer architecture before?

like image 428
Billy Avatar asked Dec 29 '22 21:12

Billy


1 Answers

I use Linq-to-SQL/XML and I consider my application to be 3 tier. The difference between a pre-Linq application is that now the data access layer is much small and lighter which is actually a very good thing!

In my old DAL I would have had methods like:

public virtual int CountCustomersInCountry(string country) {
    // Plug in raw SQL.
}

public virtual List<Customer> GetCustomersInCountry(string country) {
    // Plug in raw SQL.
}

public virtual int CountCustomersForDepartment(string department) {
    // Plug in raw SQL.
}

public virtual List<Customer> GetCustomersForDepartment(string department) {
    // Plug in raw SQL.
}

etc. etc. ad-infinitum

I now have the following sort of methods:

public virtual int Count(Expression<Func<T, bool>> where) {
    // Plug in Linq-to-SQL DataContext here.        
}

public virtual T Get(Expression<Func<T, bool>> where) {
     // Plug in Linq-to-SQL DataContext here.   
}

public virtual List<T> Get(Expression<Func<T, bool>> where,  string orderByField, int offset, int count) {
    // Plug in Linq-to-SQL DataContext here.   
}

To call the new DAL methods and with a little bit of help from DynamicLinq I use:

int countryCount = Count(c => c.Country == country);
List<Customer> customers = Get(c => c.Country == country, "inserted", 0, 25);
int departmentCount = Count(c => c.Department == department);
List<Customer> customers = Get(c => c.Department == department, "inserted", 0, 25);

And all thats before you get onto Adds, Updates and Deletes which become single line calls with Linq2SQL! My DAL now consists of 10 methods where as previously it was easy to get up to 20 to 30 methods for each object my DAL was looking after! I'd highly recommend trying to get your head around it as it really will save you a lot of code.

like image 179
sipsorcery Avatar answered Jan 01 '23 11:01

sipsorcery