views:

68

answers:

1

Hey, I have a table called products that has a relationship with itself. This table stores products, their sub-products, and then sub-sub-products. When a user searches for the top-most product, this query is supposed to return the parent, its children, and its children's children. Now, my query works, but I am new to the entity framework and SQL in general, so I am not sure if this is the way it should be done. To make things a bit more hairy, I am searching against multiple fields in the table.

else
            {
                productQuery = 
                    from b in solutionContext.Version
                    where 
                        (
                            b.Product.Name == search || b.Product.Description == search ||
                            b.Product.Product2.Name == search || b.Product.Product2.Description == search ||
                            b.Product.Product2.Product2.Name == search || b.Product.Product2.Product2.Description == search
                        )
                    orderby b.Product.LastNumber ascending
                    select b;
            }

For clarification, Product2 is the relationship that goes from the child to the parent.

Subquestion: In the future I want to a search for a child, to return its parent, and parent's parent. The way I would currently go about doing that is to add some lambda expressions and do what I did, but going up the relationship. Is that smart?

+1  A: 

There's nothing really wrong with this query. Certainly, accessing related members is expected in L2E.

Consider using syntax like:

b.Product.Name.Equals(search, StringComparison.OrdinalIgnoreCase)

Searches should generally be case-insensitive.

Craig Stuntz
Thanks, I appreciate the feedback. I knew my query was working, but since I am new to L2E I just wanted to make sure I was not doing something incorrectly or inefficiently.I like that syntax and will definitely consider using that.
PFranchise
One thing to be aware of is that L2E coalesces nulls, but L2O does not. So in your example, if `b.Product` is null, then the comparison returns `false` instead of throwing a null reference exception. It's like SQL in that way.
Craig Stuntz