Today I started to play/learn the basics on Linq2SQL and I have to say, it is pretty cool. However, within the first 20 minutes I came to a cross roads, I was stuck. I am torn between the 2 different ways to connect to, and query from, a data source. I don't know which I like better.
Below are the 2 different ways to connect, as well as my opinions as to the pros/cons on each one. Please take into account I have NO real world experience using Linq, these are just my thoughts on the subject
The most common way I have seen to use Linq2SQL is to generate a custom DataContext class (.dbml class) via the IDE. This will generate all your DTO classes for you as well as the mappings between tables/objects.
- Creates the DTO classes that map directly to your database tables for you. This can save you a bit of time versus creating the DTO's buy hand.
- When the DB schema changes, you simply have to refresh the IDE and all the changes are brought down
- No need to sprinkle your DTO's with attributes to allows Linq to use them. (ie [Table(Name="Sport")]
- The generated code creates a lot of overhead. For example, the default set code will raise 4 events as well as set the new value. If you are using these events, great, but if not you have wasted cycles.
- Gives you less control over your DTO objects
- Would NOT work well if you are trying to back in Linq2Sql into an existing application
The second way is to create a standard DataContext and create the mappings on the fly. This way does NOT generate your DTO's you
- You can use your existing DTO's (assuming you have some)
- You have 100% control over how your DTO's are created/generated
- No events are fired when you set properties, unlike the generated DTO's. This is assuming you don't WANT the events.
- Would work well in the scenario where you are trying to back Linq2Sql into an existing application.
- Because you have to hand wire the DTO's to the db tables, you become more aware of what is going one and are more able to fix 'odd' issues as the appear.
- You need to sprinkle your existing DTO's with various attributes to all them to be mapped to you database tables.
- When your DB schema changes, you need to update your DTO's by hand to reflect the changes.
- You need to use the db.GetTable<EntityHere>() (db here is a DataContext instance) in order for the context to know about a given table.
Ok so there you have it, both ways to connect to the db using Linq along with my thoughts on pros/cons. At the end of the day, I think I like the idea of Approach 2 because I like to have more control over what my code does, although I have to admit I like the auto generation capabilities of Approach 1. I wonder if my attitude with respect to which approach to use will change over time, who knows:)
Till next time,
03-13-2008 1:59 PM