Search code examples
c#entity-framework-4addition

Entity Framework refer to an entity in the DB without adding it again


I have two entities, a project and a company. One company has a list of multiple projects and a project has one company.

At this time I'm adding a existing company from the DB to project

e.g.

project.company = getCompanyByName("Microsoft");

Which returns the proper company and does add it to my project.

However, when I add this new project to the DB as such:

ctx.AddToProjects(project);
ctx.SaveChanges();

It will also add a second Microsoft company So how do I make my project refer to the existing company without adding it, again?


Solution

  • Attach the Company to the context before you associate it with a Project.

    Once the Company is safely in the context, actions that you perform on the Projects won't affect its state.