views:

175

answers:

4

What would be the best method to implement extra functionality in a database layer that uses Linq-to-SQL? Currently I'm looking at implementing functions for adding information based on presets and similar tasks?

Inserts, updates and deletes requires access to the DataContext and in the Table classes you don't have access to the context. I've seen solutions that uses Singletons but it seems like a hack and I wonder if anyone else has run into this problem and what your solutions were? Is there a better way all together to implement similar functionality.

The reason for me looking to add this functionality to the database layer is that I have several applications that all use the same database objects and I want to be able to use these functions from all applications so I don't have to rewrite a lot of code.

A: 

I hate to say it, but what about stored procedures?

On my project, whatever extra functionality we want to provide we stick in a partial class. The data context class is marked partial, so you can add methods to the context without worrying about re-generating the context nuking your work.

Will
A: 

You can use generic data context extensions for common data access methods like insert,delete etc as described in http://weblogs.asp.net/stephenwalther/archive/2008/08/26/asp-net-mvc-tip-38-simplify-linq-to-sql-with-extension-methods.aspx. and partial classes for less common funtionality as Will suggested.

aogan
A: 

That's not quite what I meant. I want to be able to do complex actions like updating one table and adding a record to another table based on information from the first one.

Say I have selected a Customer record and I want to update this with information, and when this happens I want it to add another record to the "Updates" table to keep track of when updates happened and who did them. This is only an example of course. Things needed to be done can be more complex.

Basically I want to add a method to a table object to perform modifications to a specific row in that table and then do inserts and updates on other objects. I know that you can use partial classes and I do that extensively already.

Example:

db.Customers.Where(c => c.CustomerID == 5).AddOrder(orderDetails);

I feel that I can't really put my problem into words to make it understandable :)

Kristoffer L
Not to be a jerk, but if you're having a hard time putting what you want to do in words, you should fundamentally reexamine the design path you're going down.For complex actions based on table values, you would extend your DataContext with its partial methods...
Dave Markle
+1  A: 

Entity classes in Linq to SQL are partial. You could extend them with the rules you need.

Or you could build your own business entities from the Linq to SQL entities. Your business entities would then contain the rules on when to do what.

Thomas Eyde