views:

89

answers:

2

Here is the expression

x => x.stf_Category.CategoryID == categoryId

x refers to an Product Entity that contains a Category. I am trying to load all Products that match given categoryId.

In the db the Product table contains a Foreign Key reference to Category (via CategoryId).

Question: I think I am doing it wrong. Is there something else one has to do in EF4 to create a LINQ expression of this type?

Are there any good examples of EF4 Linq expressions out there? Specifically something that queries on the basis of related entities such as my problem ?

Thanks !

+1  A: 

You're looking for the Include method.

var query = db.Products.Include("Categories");

This is commonly referred to as eager loading.

Entity Framework will 'infer' the JOIN constraint based on the mapping you have specified.

The "magic string" needs to match the Entity Set name on your EDMX.

Check out this post for more info.

EDIT

I'm a little confused as to whether you want the Products and Categories, or just the Products which have a specific Category ID.

If the latter, this is the way to go:

var query = from p in db.products
            join c in db.categories
            on p.CategoryId equals c.CategoryId
            where c.CategoryId == someCategoryId
            select p;

Keep in mind though, the above query is exactly the same result as your original query.

If p is a product, then p.Categories will look at the Navigational Property of your Product entity on the EDMX, in which case it will be your Category FK.

As long as you setup your Navigational properties right, p.Categories is fine.

RPM1984
For what its worth I will also try another workaround. Since this is a display list I will pull the necessary data into a View in the db and use that. It will make the expression simpler I am sure. Appreciate the responses and links!
etechpartner
I agree, we also use views for common queries, makes the LINQ much more robust.
RPM1984
A: 

If you are using EF4 and the association between Category and Product classes has been picked up and defined in your Model, then all products with a specific categoryID can be selected as simple as:

x => x.CategoryID == categoryID

You don't need to join nor an eager loading for that.

Morteza Manavi
If x is a Product (as he states), then it wont have a property called "CategoryID" - it's inside the Categories navigational property.
RPM1984
In EF 4, an important new feature was added: **Foreign Key Support**. In a classic Entity Relationship Model, foreign keys are not exposed in the conceptual model. EF followed this paradigm in .NET 3.5 SP1 meaning that you did not have direct access to the FK property. Well, not anymore. Please take a look at this: http://blogs.msdn.com/b/efdesign/archive/2009/03/16/foreign-keys-in-the-entity-framework.aspx
Morteza Manavi