Monday, July 28, 2008

Reading Source, Minima III

{

As my reading of Minima source code continues I wanted next to comment upon the database interaction which is novel (to me at least) in that it is exclusively a LINQ implementation with no stored procedure or ADO.NET implementation.  I've seen LINQ quite a bit, but many using it seem to stick to using the query syntax rather than using raw lambda expressions.  All the LINQ in Minima that I've seen uses lambda expressions and I've  come to appreciate it as a clean, sparse syntax.  To illustrate a more trivial example, assuming I have a table Users with Username / Password columns I wanted to verify for access. The first step with all things LINQ is to make your data model, which amounts to a DBML file that you map database objects to with drag and drop. Next you can write query expressions to pull data out of the database - notice that the db variable here points to the data model as embodied in a "data context" object:

            var authUserQuery = from u in db.Users 
where u.Email == Login1.UserName && u.Passphrase == Login1.Password
select u;


Unfortunately the query expressions return an IEnumerable<T> that doesn't support a Count or Length property. It's a somewhat inflexible thing that in my *very* limited experience is useful mainly for iterating with a ForEach - and I suspect it's reasons like this that led Betz to using a lambda syntax that is much cleaner and gets more bang with less code:



            Func<Data.User, Boolean> checkUser = x => x.Email == Login1.UserName && x.Passphrase = Login1.Password;
Data.User u = db.Users.SingleOrDefault(checkUser);


You can use nullability to test for the presence of a record based on the LINQ query. Some source from Minima that demonstrates this is verification of the existence of a blog author:



            Func<AuthorLINQ, Boolean> authorExists = x => x.AuthorEmail == authorEmail;
authorLinq = db.Authors.SingleOrDefault(authorExists);
if (authorLinq == null)
{
throw new ArgumentException(message);
}


It's truly novel and I don't mean to make that sound like a trivial or ornamental type "novel" I write; after spending so much time building a data access layer with stored procedures and ADO.NET (Connection, Command, Reader, DataSet, ad nauseum) it seems like our collective destiny is to walk away from that and let something like a DBML data context do black magic for us.



Even though the ADO.NET Entity Framework is getting a FAIL vote from some people, I'm interested to see how this overlaps with LINQ. Even after listening to Hanselman's interview of Mike Pizzo I'm still a little unclear. My plan of action is to get serious about NHibernate to try to understand, as Scott would say, "the gestalt" of an ORM and then make the call on ADO.NET Entity Framework when it's released.



}

No comments: