Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6184111
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T01:28:47+00:00 2026-05-24T01:28:47+00:00

In our application we use the repository pattern to retrieve and persist data from

  • 0

In our application we use the repository pattern to retrieve and persist data from our data storage medium. The medium we opted to use is Entity Framework 4. This seems to be a very clean way to do things and has worked great 99% of the time.

Now we are encountering an issue. We have two repositories, like this:

public class UserRepository : IUserRepository
{
    Entities dataContext = new Entities();

    public User GetUser(string username)
    {
        return dataContext.Users.SingleOrDefault(x => x.Username == username);
    }

    // ... more CRUD-style methods that are not relevant to this question.

    public void SaveChanges()
    {
        dataContext.SaveChanges();
    }
}

public RoleRepository : IRoleRepository
{
    Entities dataContext = new Entities();

    public Role GetRole(string name)
    {
        return dataContext.Roles.SingleOrDefault(x => x.Name == name);
    }

    // ... more CRUD-style methods that are not relevant to this question.

    public void SaveChanges()
    {
        dataContext.SaveChanges();
    }
}

Users and Roles actually have a many to many relationship in the Entity Framework model. Sometimes we want to take an existing user and an existing role and associate the two. Normally this would work great if you do a short sample code snippet like this:

Entities dataContext = new Entities();
Role roleToAdd = dataContext.Roles.Single(x => x.Name == "Admin");
User user = dataContext.Users.Single(x => x.Username == "Fred");
user.Roles.Add(roleToAdd);
dataContext.SaveChanges();

This works great because both entities are being retrieved from the same EF data context object. However, in our application each repository creates its own data context object. So when we try to do the same as the above with our own architecture:

UserRepository userRepo = new UserRepository();
RoleRepository roleRepo = new RoleRepository();
User user = userRepo.GetUser("Fred");
Role roleToAdd = roleRepo.GetRole("Admin");
user.Roles.Add(roleToAdd);
userRepo.SaveChanges();

We get this error:

The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects.

What is the best way to centralize this data context? Obviously I don’t want to duplicate a GetRole method within the UserRepository because that would be redundant and silly. I could just do a more verbose method on the UserRepository that takes in a username and a rolename, then uses the same data context to retrieve and associate them, like this:

public void AddUserToRole(string username, string role)
{
    User user = dataContext.Users.Single(x => x.Username == username);
    Role roleToAdd = dataContext.Roles.Single(x => x.Name == role);
    user.Roles.Add(roleToAdd);
}

I could then just do:

userRepo.AddUserToRole("Fred", "Admin");
userRepo.SaveChanges();

But is that the best way to accomplish this? Is there a better way to centralize the EF data context on each request so that all repositories use the same one instead of creating their own? If so, how would I do that?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-24T01:28:48+00:00Added an answer on May 24, 2026 at 1:28 am

    Use constructor injection on the repository to pass the context.

    public class UserRepository : IUserRepository
    {
        Entities dataContext;
    
        public UserRepository(Entities entities)
        {
           this.dataContext = entities;
        }
    
        public User GetUser(string username)
        {
            return dataContext.Users.SingleOrDefault(x => x.Username == username);
        }
    
        // ... more CRUD-style methods that are not relevant to this question.
    
        public void SaveChanges()
        {
            dataContext.SaveChanges();
        }
    }
    

    Tell your DI container to request-scope the context lifetime.

    E.g., with AutoFac you would:

    builder.RegisterType<Entities>().InstancePerHttpRequest();
    builder.RegisterType<UserRepository>().As<IUserRepository>().InstancePerHttpRequest();
    builder.RegisterControllers(typeof(MvcApplication).Assembly);
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Hereabouts, we use a Sonatype Maven repository. This is jolly nice for our maven
For displaying data in our application I've use GridView with the following markup: <asp:GridView
The application i am currently working on makes heavy use of the repository pattern
In our application we use std::map to store (key, value) data and use serialization
Have Log4Net configured in our application to use a date stamped name and a
In our Spring application we use clustered Hibernate Search with ActiveMQ which sets up
Our application used to make use of a common base form that all forms
We use OpenFileDialog across our application to select files. So far, we never used
We're planning to use standard ASP.NET user authentication for our application. However, by default
We are in the process of migrating our ASP.NET application to use Jquery instead

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.