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

  • Home
  • SEARCH
  • 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 6471637
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T06:14:50+00:00 2026-05-25T06:14:50+00:00

I have three tables that I am working with User, Application, ApplicationAdministrator. ApplicationAdministrator is

  • 0

I have three tables that I am working with User, Application, ApplicationAdministrator. ApplicationAdministrator is a mapping table to link User to Application which has a many-to-many relationship. I get the following error when I try to save off a new Application with a User added as an Administrator:

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

So my next step was to create a BaseRepository that has a common context to pull from. However, now I get the following error when I try to modify an entity that is already attached to the context:

An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.

Why is this such a difficult process? I have seen the solutions to attach and reattach and detach and spin around on your head 5 times and then everything will work. Attaching the entities to one context ends up duplication one of the entities depending on which context I attach it to.

All help is greatly appreciated!

UserRepository.cs:

public class UserRepository : BaseRepository<User>, IUserRepository
{
    // private ManagerDbContext _context = new ManagerDbContext();

    public UserRepository(ManagerDbContext context)
        : base(context) { }

    public IQueryable<User> Users
    {
        get { return _context.Users.Include("Administrates").Include("Company"); }
    }

    public void SaveUser(User user)
    {
        _context.Entry(user).State = user.Id == 0 ? EntityState.Added : EntityState.Modified;

        _context.SaveChanges();
    }

    public void DeleteUser(User user)
    {
        _context.Users.Remove(user);

        _context.SaveChanges();
    }
}

ApplicationRepository.cs:

public class ApplicationRepository : BaseRepository<Application>, IApplicationRepository
{
    // private ManagerDbContext _context = new ManagerDbContext();

    public ApplicationRepository(ManagerDbContext context)
        : base(context) { }

    public IQueryable<Application> Applications
    {
        get { return _context.Applications.Include("Administrators"); }
    }

    public void SaveApplication(Application app)
    {
        _context.Entry(app).State = app.Id == 0 ? EntityState.Added : EntityState.Modified;
        _context.SaveChanges();
    }

    public void DeleteApplication(Application app)
    {
        _context.Applications.Remove(app);
        _context.SaveChanges();
    }
}

UserConfiguration.cs:

public UserConfiguration()
{
    this.HasKey(x => x.Id);

    this.Property(x => x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
    this.Property(x => x.FirstName).IsRequired();
    this.Property(x => x.LastName).IsRequired();
    this.Property(x => x.Username).IsRequired();
    this.Property(x => x.CompanyId).IsRequired();

    this.HasRequired(user => user.Company).WithMany().HasForeignKey(user => user.CompanyId);
    this.HasRequired(user => user.Company).WithMany(company => company.Users).WillCascadeOnDelete(false);

    this.HasMany(user => user.Administrates)
        .WithMany(application => application.Administrators)
        .Map(map => map.MapLeftKey("UserId")
            .MapRightKey("ApplicationId")
            .ToTable("ApplicationAdministrators"));
}

ApplicationConfiguration.cs:

public ApplicationConfiguration()
{
    this.HasKey(x => x.Id);

    this.Property(x => x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
    this.Property(x => x.Name).IsRequired();
    this.Property(x => x.Description);

    this.HasMany(application => application.Administrators)
        .WithMany(user => user.Administrates)
        .Map(map => map.MapLeftKey("ApplicationId")
            .MapRightKey("UserId")
            .ToTable("ApplicationAdministrators"));
}

Snippet for saving the entities.

long appId = Int64.Parse(form["ApplicationId"]);
long userId = Int64.Parse(form["UserId"]);

Application app = appRepository.Applications.FirstOrDefault(a => a.Id == appId);
User user = userRepository.Users.FirstOrDefault(u => u.Id == userId);

app.Administrators.Add(user);

appRepository.SaveApplication(app);

return RedirectToAction("Index");
  • 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-25T06:14:50+00:00Added an answer on May 25, 2026 at 6:14 am

    Here is my solution that I finally came up with.

    I created a Func dictionary in order to attach an entity to the correct EntitySet in my context. The one downfall is that you have to hard code the EntitySet name some, so I did it in a static variable within my POCO.

    BaseRepository.cs

    public class BaseRepository<T> where T : class 
    {
        public static ManagerDbContext baseContext;
    
        public BaseRepository() { }
    
        public BaseRepository(ManagerDbContext context)
        {
            baseContext = context;
        }
    
        private static object _entity;
    
        public void AttachEntity(object entity)
        {
            _entity = entity;
    
            entityAttachFunctions[entity.GetType().BaseType]();
        }
    
        private Dictionary<Type, Func<bool>> entityAttachFunctions = new Dictionary<Type, Func<bool>>()
        {
            {typeof(User), () => AttachUser()},
            {typeof(Application), () => AttachApplication()}
        };
    
        private static bool AttachUser()
        {
            ((IObjectContextAdapter)baseContext).ObjectContext.AttachTo(User.TableName, _entity);
    
            return true;
        }
    
        private static bool AttachApplication()
        {
            ((IObjectContextAdapter)baseContext).ObjectContext.AttachTo(Application.TableName, _entity);
    
            return true;
        }
    }
    

    UserRepository.cs

    public void AttachEntity(object entity)
    {
        baseContext = _context;
    
        base.AttachEntity(entity);
    }
    
    public void DetachUser(User user)
    {
        _context.Entry(user).State = EntityState.Detached;
    
        _context.SaveChanges();
    }
    

    ApplicationRepository.cs

    public void AttachEntity(object entity)
    {
        baseContext = _context;
    
        base.AttachEntity(entity);
    }
    
    public void DetachApplication(Application app)
    {
        _context.Entry(app).State = EntityState.Detached;
    
        _context.SaveChanges();
    }
    

    AdminController.cs

    long appId = Int64.Parse(form["ApplicationId"]);
    long userId = Int64.Parse(form["UserId"]);
    
    Application app = appRepository.Applications.FirstOrDefault(a => a.Id == appId);
    User user = userRepository.Users.FirstOrDefault(u => u.Id == userId);
    
    userRepository.DetachUser(user);
    
    appRepository.AttachEntity(user);
    
    app.Administrators.Add(user);
    
    appRepository.SaveApplication(app);
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a table that has three different date columns, so I set each
I have three tables like that: Articles IdArticle Title Content Tags IdTag TagName ContentTag
I have three tables in my DB (actually a few more than that) these
I have a Microsoft SQL Server 2008 query that returns data from three tables
In my table I have looked manually and found that the top three idle
I have content management system application that uses a polymorphic tree table as the
Suppose I have a table called Companies that has a DepartmentID column. There's also
I'm working on an application that has similar logic as SO with regards to
I'm working on an application which has different types of users i.e. students, tutors,
I'm working on a web application that will be a hosted, multi-user solution when

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.