Linq Foreign Key Select

c# entity-framework-6 linq

Question

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.

1
2
3/17/2015 3:03:46 AM

Popular Answer

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();
1
3/17/2015 3:36:22 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow