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 8018057
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T21:01:41+00:00 2026-06-04T21:01:41+00:00

I am using Entity Framework 4.3 and I am trying to reference an existing

  • 0

I am using Entity Framework 4.3 and I am trying to reference an existing entity by setting the navigation property when creating a new entity, however when i call save EF complains that there is a PK violation in the table for which i set the navigation property to (i.e. it is creating a new record as opposed to a reference!).

How can i attach to an existing POCO as opposed to referencing it and having EF trying to create a new database record (but not simply use an ID, ideally i would like to reference an actual entity that came from another query)?

Thanks in advance,

Chris

public class BusinessUnit
{
    public int BusinessUnitID { get; set; }
    public ExternalPlugin AccountsDataSourceModule { get; set; }
    public ExternalPlugin OptionalContactsDataSourceModule { get; set; }
}

public BusinessUnit NewBusinessUnit(string name, ExternalPlugin accountsModuleId = null, ExternalPlugin contactsModuleId = null)
{
    IUnitOfWork unitOfWork = UnitOfWorkFactory.CreateUnitOfWork();

    BusinessUnit unit = new BusinessUnit();
    unit.CompanyName = name;
    unit .AccountsDataSourceModule = accountsModuleId; // this causes a problem
    unit .OptionalContactsDataSourceModule = contactsModuleId; // as does this
    unitOfWork.BusinessUnitRepository.Insert(unit);

    unitOfWork.Save();
    return unit;
}
  • 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-06-04T21:01:42+00:00Added an answer on June 4, 2026 at 9:01 pm

    You must attach the existing entities to the context:

    BusinessUnit unit = new BusinessUnit();
    unit.CompanyName = name;
    
    unitOfWork.ExternalPluginRepository.Attach(accountsModuleId);
    unitOfWork.ExternalPluginRepository.Attach(contactsModuleId);
    
    unit.AccountsDataSourceModule = accountsModuleId;
    unit.OptionalContactsDataSourceModule = contactsModuleId;
    unitOfWork.BusinessUnitRepository.Insert(unit);
    

    …where unitOfWork.ExternalPluginRepository.Attach(ExternalPlugin plugin) must do:

    context.ExternalPlugins.Attach(plugin);
    

    I expect that all repositories use the same context instance. Attach tells EF that the plugins already exist in the database and avoids an INSERT of those entities.

    Edit

    If you get the error message…

    An entity object cannot be referenced by multiple instances of
    IEntityChangeTracker.

    …it means that you have an entity that is attached to more than one context instance at the same time. You can avoid that in most cases by disposing the context always when you don’t need it anymore. Your code sample does not follow this good practice. It rather should look like this:

    public BusinessUnit NewBusinessUnit(string name,
        ExternalPlugin accountsModuleId = null,
        ExternalPlugin contactsModuleId = null)
    {
        using (IUnitOfWork unitOfWork = UnitOfWorkFactory.CreateUnitOfWork())
        {
            BusinessUnit unit = new BusinessUnit();
            unit.CompanyName = name;
    
            unitOfWork.ExternalPluginRepository.Attach(accountsModuleId);
            unitOfWork.ExternalPluginRepository.Attach(contactsModuleId);
    
            unit.AccountsDataSourceModule = accountsModuleId;
            unit.OptionalContactsDataSourceModule = contactsModuleId;
            unitOfWork.BusinessUnitRepository.Insert(unit);
    
            unitOfWork.Save();
    
            return unit;
        }
    }
    

    At the end of the using block the Dispose method of the unitOfWork is called automatically. To get this working (and compiling as well) you need to derive your IUnitOfWork interface from IDisposable and implement it in the concrete UnitOfWork class:

    public interface IUnitOfWork : IDisposable
    {
        // ...
    }
    
    public class ConcreteUnitOfWork : IUnitOfWork, IDisposable
    {
        private MyDbContext _context;
        // I assume that you have a member for the DbContext in this class
        // ...
    
        // implementation of IDisposable
        public void Dispose()
        {
            if (_context != null)
                _context.Dispose();
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am using Entity Framework 4.3.1 and I am trying to insert a new
Trying to map the following schema using the Entity Framework. A Customer can have
I keep getting an InvalidProgramException trying to grab data through the entity framework. using
I'm trying to use MySQL (5.5.22, Connector 6.5.4) with Entity Framework 4. I'm using
When using Entity Framework 4.1, are there alternatives to the naming conventions for Navigation
I've been trying to implement POCO over WCF (using Entity Framework 4.0) - just
I'm trying to understand some fundamental best practices using Entity Framework. My EDM design
I'm using the entity framework that comes with 3.5sp1, and I'm trying to add
I have been using Entity Framework 4.3 on an existing database and I have
I am trying use MySql and Entity Framework, using Connector/Net 6.1 with this as

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.