Geeks With Blogs

News Photo of Tanzim Saqib Tanzim Saqib is a Senior Developer, who spent half of his life on software and worked for many companies like #1 .NET controls provider Telerik Inc, #1 personalized Web 2.0 start-page like Pageflakes (acquired by LiveUniverse). He developed many projects ranging from banking solutions for Citibank, HSBC, Wamu, Wells Fargo etc. to Paperless Virtual University. He is industry's earliest and leading widget developer and as know as "Widget Master" to his peers.

He is a preacher of Microsoft technologies. While he jams with the latest additions to .NET, in his spare time he blogs at http://weblogs.asp.net/TanzimSaqib, maintains his personal website http://www.TanzimSaqib.com, leads .NET Research group. writes articles.

He is an easy going, fun loving, and passionate technology individual who is open to any kind of business opportunity and professional relationship. He currently lives in Bangladesh, but travels anywhere in the world on professional demand.

Email: me at TanzimSaqib dot com

Tanzim Saqib on .NET discovery Innovate. Create. Share.

In LINQ to SQL, the data model of a relational database is mapped to an object model expressed in the programming language of the developer. When the application runs, LINQ to SQL translates into SQL the language-integrated queries in the object model and sends them to the database for execution. When the database returns the results, LINQ to SQL translates them back to objects that you can work with in your own programming language. You may want to make a data access layer that separates the data operation from business layer like the following:

DbHelper.Insert<Student>(
    new Student()
    {
        FirstName = “Tanzim”,
        LastName = “Saqib”,
        Email = “me@TanzimSaqib.com”,
        Website = “http://www.TanzimSaqib.com”
}, true);    // Use Transaction?

To make use of such transactional generic DbHelper, you might want to write a singeton DbHelper class like the following. You might notice that the class is singleton, it’s static and the DataContext is being used is private, and only initialized using the connection string if not yet.

public static class DbHelper
{
    private const string CONNECTION_CONFIG_NAME = “StudentServerConnectionString”;

    private static StudentServerDataContext _StudentServerDataContext = null;

    public static StudentServerDataContext GetDataContext()
    {
        if(_StudentServerDataContext == null)
            _StudentServerDataContext = new StudentServerDataContext
                (ConfigurationManager.ConnectionStrings
                [CONNECTION_CONFIG_NAME].ConnectionString);

        return _StudentServerDataContext;
    }

    public static void CleanUp()
    {
        _StudentServerDataContext.Dispose();
        _StudentServerDataContext = null;
    }

    // … code edited to save space

On application wide error or on end you can dispose the context so CleanUp method is useful here. To implement an Insert method see the following. You will find I have used a TransactionScope which ensures that the transaction is taking place without any interruption. If there is really any error the scope.Complete() method never gets invoked. This is how it ensures that the code inside the TransactionScope is taking place as a transaction. It is available from .NET 2.0 framework.

public static void Insert<T>(T t, bool isTransactional) where T : class
{
    if (isTransactional)
    {
        using (var scope = new TransactionScope())
        {
            Insert<T>(t);

            // On any Exception, Complete() method won’t be invoked.
            // So, the transaction will be automatically rollbacked.
            scope.Complete();
        }
    }
    else
        Insert<T>(t);
}

public static void Insert<T>(T t) where T : class
{
    using (var db = GetDataContext())
    {
        db.GetTable<T>().InsertOnSubmit(t);

        try
        {
            db.SubmitChanges();
        }
        catch (Exception e)
        {
            // TODO: log Exception
            throw e;
        }
    }
}

I did not show other methods as part of the CRUD implementation. The rest is left open for you to implement.

Posted on Friday, February 29, 2008 8:29 AM LINQ , SQL , .NET , C# | Back to top


Comments on this post: A "transactional" generic DbHelper for LINQ to SQL

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Tanzim Saqib | Powered by: GeeksWithBlogs.net