Alex Rivera | Logout

Can LINQ to SQL generated objects be decoupled?

Asked 2008-10-21T18:17:28.043
11

I like LINQ to SQL, but it seems like the classes it generates are tightly coupled to the database they are stored in, which seems like a Bad Thing.

For example, using ye olde Northwind database, if I create the dbml with the Products table, a Product class is generated. I can use this class in any other tier, which is all well and good, but if I decide I'd rather use plain old ADO.NET (or switch databases), I'll have to recreate the Product class, along with every other "model."

Is there a way around this? Or to create your object models separately, and then have the tables mapped to them? I've played around with the various mapping classes provided, but haven't found a satisfactory answer yet.

Edit
Report

2 Answers

2

I've recently achieved this by creating the POCOs myself and manually creating a XML mapping file for the database. It requires a bit of manual work but it gives the desired effect.

Here's a blog post I found useful to get you started.

answered 2008-10-21T22:45:13.107
2

Oh hey, I think I found a solution to this while watching Rob Conery's screencasts on ASP.NET MVC. The trick is to select into an object in your LINQ to SQL query.

public IQueryable<LinqExample.Core.Person> GetAll() {
    var people = from pe in this.db.Persons
                 select new Person {
                     Id = pe.id,
                     FirstName = pe.fname,
                     LastName = pe.lname,
                     Reports = this.GetReports(pe.id)
                 };
    return people;
}

This let's you define a Person class elsewhere in your code. I blogged about it more in depth.

answered 2008-12-12T21:05:26.533

Your Answer