user1760623
user1760623

Reputation:

Linq Foreign Key Select

I have two tables with a one (Articles) to many (Details) relationship. Details may not contain any data for the particular Article entry.

Articles: Id, Title, Numb (PK), Name

Details: Id (PK), Person, Numb (FK), Name

In the Entity Framework, there are the appropriate Navigation properties and it shows the correct One:Many relationship.

What I want to do is get all Articles that match the end user's query (by 'Name') as well as all, if any, data from the Details table (Id, Person, Numb, Name).

What I'm stuck on is right now I can query Articles just fine (var article = db.Articles.Where(b => b.Name.Equals(name));), but while the result does include a HashSet for Details.Numb on each row of Articles, there is no data in that HashSet. There are appropriate corresponding entries in the database for Article.Numb => Details.Numb.

Upvotes: 2

Views: 22535

Answers (4)

Vahid Amiri
Vahid Amiri

Reputation: 11117

Example:

var allProducts = _db.Products.Include(d => d.Producer).ToList();

Always go with Include instead of lazy loading if you're not sure.

Upvotes: 0

Jenish Rabadiya
Jenish Rabadiya

Reputation: 6766

Actually there is two ways to achieve this.

  1. Enable Lazy Loading.
  2. Call Include method as other answers says.

Using Lazy Loading see msdn article for more detail.

    db.ContextOptions.LazyLoadingEnabled = true;

Using Include method

    var article = db.db.Articles.Include("Details").Where(b => b.Name.Equals(name))).FirstOrDefault();

Upvotes: 1

Blindy
Blindy

Reputation: 67362

Use .Include() on the navigation property, it will bring the entire inner object in the query result. It's only automatic if you filter or select items from the inner object, otherwise you have to manually request an include.

Upvotes: 0

Jason W
Jason W

Reputation: 13179

You need to tell EF to include the details in the result set after the query is executed (and connection closes):

var article = db.Articles
    .Include("Details")
    .Where(b => b.Name.Equals(name))
    .FirstOrDefault();

Upvotes: 0

Related Questions