Kashif
Kashif

Reputation: 14430

Entity Framework 4: Fetching data of two table and returning to persentation layer

I have two tables having 1 to 1 relationship. One table called Person and second is PersonDetails. PesonId is in PersonDetails table as FK.

I can query individual tables like

public static Person GetPersonById(int personId)
{
    using (var context = new REntities())
    {
    return context.Person.Where(p => p.PersonId == personId).First();
    }
}

It is being used in consuming code like:

Person personInfo = PersonService.GetPersonById(personId);

and same with PersonDetail on its PK i.e. PersonDetailId

But when I have to fetch data from two tables then I am not understanding that what how would I do this and what would be the best way to return data to presentation layer.

Following would be the code to get Person and relate PersonDetails records:

from personData in context.person.Include("PersonDetail")
                                  where personData.PersonId == personId
                                  select personData;

What is personData here? How can I iterate over it and get each item in client code?

Thanks.

Upvotes: 0

Views: 2203

Answers (2)

NinjaNye
NinjaNye

Reputation: 7126

If you are using Entity Framework Code First (EF 4.1), mark the PersonDetails property in the Person class as virtual. This will enable EF to populate the data automatically so you can simply do person.PersonDetails to get your list of data

Upvotes: 0

MNIK
MNIK

Reputation: 1619

When you get your Person object, you can include the PersonDetails object as well within the query like this...

using (var context = new REntities())
{
  return context.Person.Include("PersonDetail").Where(p => p.PersonId == personId).First();
}

Now on the presentation side, when you get the Person object, iterate through each item of person detail like this...

from p in personInfo.PersonDetails
select p; // here p is the person detail object

Hope it helps.

Upvotes: 1

Related Questions