Microsoft Study Bible

October 28, 2009

LINQ to SQL common BaseClass

LINQ is a series of new features provided by Visual Studio 2008, which will expand C# and Visual Basic and can provide powerful query capabilities. As part of LINQ, LINQ to SQL can provide a framework on which the relational data is used as object to run. In one way, it is equal to NHibernate and Castle provided by Microsoft. When we need to access the database, LINQ to SQL will become our first choice.

In LINQ to SQLall varies in relational database model are strongly typed ,which can provide verification and intelisense when they are being complied .And we can use Query expression including query syntax and method syntax, to access data from the database.

 

1. Achieve where method

 

 Howeverthe strongly-typed is not beneficial to do abstract operation on the data .So, the developer had to define some particular class for each entity object, which will cause to a lot of duplicate code .If we can achieve a common BaseClass and encapsulate Public Data operation such as Select ,Where ,Add ,Update and Delete ,it can be useful for us to develop the N-tier application development.

Fortunately, Generics Types can help us make it .The way is to call GetTable<T>() method of  DataContext .For example ,we can achieve where method by passing a Lambda expression to find the result we want to get.

 public IList<TEntity> Where(Func<TEntity, bool> predicate)
{
    InitDataContext();
    
return
m_context.GetTable<TEntity>().Where(predicate).ToList<TEntity>();
}

 

Andwe can even use Dynamic Query to expose some methods to receive conditional expression

public static class DynamicQueryable
{
    
public static IQueryable<T> Where<T>(this IQueryable<T> source, string predicate, params object
[] values)
    {
        
return
(IQueryable<T>)Where((IQueryable)source, predicate, values);
    }
public static IQueryable Where(this IQueryable source, string predicate, params object
[] values)
    {
        
if (source == null) throw new ArgumentNullException(“source”
);
        
if (predicate == null) throw new ArgumentNullException(“predicate”
);
        LambdaExpression lambda = DynamicExpression.ParseLambda(source.ElementType,
typeof(bool
), predicate, values);
        
return
source.Provider.CreateQuery(
            Expression.Call(
                
typeof(Queryable), “Where”
,              
                
new
Type[] { source.ElementType },
                source.Expression, Expression.Quote(lambda)));
    }
}
public IList<TEntity> Where(string predicate, params object
[] values)
{
    InitDataContext();
    
return
m_context.GetTable<TEntity>().Where(predicate, values).ToList<TEntity>();
}

 

Data Entity operation

Of course, for an AbstractBaseClass, there is no problem to query .Because there is no need to care the properties of the entity or the composition of the expression Lambda when we call these methods. (more…)

Powered by WordPress

Close
E-mail It