LINQ to SQL Extension Methods

LINQ to SQL is a powerful component of .NET, however, I often find myself duplicating the same code across projects. I created the following extension methods to make common operations easier to use. The class adds generic methods for Delete(), Save(), Exists(), and IsAttached().

public static class LinqExtensions {
    public static void Delete<T>(this Table<T> table, T entity) where T : class {
        if (table.IsAttached(entity) == false)
            table.Attach(entity);

        table.DeleteOnSubmit(entity);
        table.Context.SubmitChanges();
    }

    public static Boolean Exists<T>(this Table<T> table, T entity) where T : class {
        return (table.Where(e => e == entity).Count() > 0);
    }

    public static Boolean IsAttached<T>(this Table<T> table, T entity) where T : class {
        return (table.GetOriginalEntityState(entity) != null);
    }

    public static void Save<T>(this Table<T> table, T entity) where T : class {
        if (table.Exists(entity))
            if (table.IsAttached(entity) == false)
                table.Attach(entity);

            table.Context.Refresh(RefreshMode.KeepCurrentValues, entity);
        }
        else
            table.InsertOnSubmit(entity);

        table.Context.SubmitChanges();
    }
}

The IsAttached() method is required to make sure that the data context has the entity before any other operation is attempted. The method GetOriginalEntityState() will return null if the entity is not in the context (if it’s not in the context, the original state is unknown – null).

Exists() will query the underlying table for matching entities. If it can’t find any it knows that the entity is new. This is important for the Save() method, as inserts and updates are handled differently.

In a production environment you would, of course, want to add validation and error handling. To keep the code focused and simple they were omitted in this example.

× Comments are closed.