views:

73

answers:

1
 Dim entName = "Some Auto Dealer"
    Dim whereEntity As Expression(Of Func(Of Entity, Boolean)) = Function(en) en.ENTY_Name = entName
    Dim login = Repository(Of Entity).Create().FindSingle(whereEntity)

    Dim whereDealer As Expression(Of Func(Of Dealer, Boolean)) = Function(dlr) dlr.Entity.Equals(login)
    Dim dealer = Repository(Of Dealer).Create().FindSingle(whereDealer)

    Dim whereContract As Expression(Of Func(Of MBI_Contract, Boolean)) = Function(c) c.Dealer.Equals(dealer) AndAlso c.Vehicle.Make.Equals(ford)
    Dim fordContractsFromPSAuto = Repository(Of MBI_Contract).Create().FindAll(whereContract).ToList()

How can I write this better? It works and it's pretty fast, but it seems kind of overkill to me. The FindSingle and FindAll take Expression(Of Func(Of T, Boolean)) as an arg for the Where clause. This is my first dabble at writing Lambda expression so please forgive me if it looks bad.

Note Repository is a generic class and Create is a factory method that returns a DataContext object. This application is using LinqToSql.

Thanks for any advice. Cheers, ~ck in San Diego

+1  A: 

I'm a C# programmer, so I'm sorry if this suggestion doesn't really apply; In C#, I would typically use one line that contains the lambda and the method call; eg:

var login = Repository<Entity>.Create().Single(en => en.ENTY_Name == entName);

I think you could do something similar in VB like:

Dim login = Repository(Of Entity).Create().FindSingle( _
    Function(en) en.ENTY_Name = entName)

This probably comes down to personal preference though...

As an alternative, you could rewrite the whole thing using the query-like syntax; I don't use it very often so I can't convert your very quickly, but it'd be more like:

Dim contract = From c in Repository(Of MBI_Contract) _
    join d in Repository(Of Dealer) on c.Dealer equals d _
    where d.Entity.ENTY_Name = entName _
    select c
Chris Shaffer
Cool. Thanks for the advice. :)
Hcabnettek