Chris Roberts
Chris Roberts

Reputation: 18802

Accessing other entities from an EF Code-First POCO

I have a data model which I've created using Entity Framework Code First POCO objects.

In one of my classes, I'd like to add a method 'GetUsefulInfo'.

In order to implement this method, I need to run queries against other entities in the data model.

The question is, how should I get hold of the data context from within this method? Do I need to pass it in as a parameter to the method? It feels like there should be a way to implement this without having to ask the consumers of this class do this?

Thanks, - Chris

Upvotes: 1

Views: 110

Answers (1)

Leniel Maccaferri
Leniel Maccaferri

Reputation: 102448

This looks like a good fit for a UserRepository.

Generally the repository holds a reference to your context using some kind of dependency injection or just a private reference to your DataContext.

There you can query whichever repository to gather the required information.

Sample code:

public class UserRepository : IUserRepository
{
    private readonly EntityFrameworkDataContext database =
                                                     new  EntityFrameworkDataContext();

    public User GetUserFullInfo()
    {
        try
        {
            // Your DataContext queries to return the User and all his info...
        }
        catch
        {
            // Whaterver...
        }
    }

}

Upvotes: 1

Related Questions