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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T04:55:47+00:00 2026-06-17T04:55:47+00:00

Im wanting to use Entity Framework POCO in a disconnected (from context) mode. In

  • 0

Im wanting to use Entity Framework POCO in a disconnected (from context) mode. In my scenario I’m creating a new Parent object and want to attach an existing child object to it and then save it to the db.
The code below undesirably inserts a new Course record when saving a new Student record, when instead I want the existing Course record linked to the new Student record.

How can I do this in Entity Framework where…

  • the objects can be disconnected from the context. (i.e. Queried in one context and then saved in a different context)
  • I dont need to re-query the child record from the DB just so I can attach it to the parent when I’m saving to db. I really want to avoid doing extra trips to the db when I already have it as an object in memory.

This page shows a database diagram that the code below is based on http://entityframeworktutorial.net/EF4_EnvSetup.aspx#.UPMZ4m-UN9Y

class Program
{
    static void Main(string[] args)
    {

        //get existing course from db as disconnected object
        var course = Program.getCourse();

        //create new student
        var stud = new Student();
        stud.StudentName = "bob";

        //assign existing course to the student
        stud.Courses.Add(course);

        //save student to db
        using (SchoolDBEntities ctx = new SchoolDBEntities())
        {
            ctx.Students.AddObject(stud);
            ctx.SaveChanges();
        }
    }

    static Course getCourse()
    {
        Course returnCourse = null;

        using (var ctx = new SchoolDBEntities())
        {
            ctx.ContextOptions.LazyLoadingEnabled = false;
            returnCourse = (from s in ctx.Courses
                            select s).SingleOrDefault();
        }

        return returnCourse;
    }
}
  • 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-17T04:55:48+00:00Added an answer on June 17, 2026 at 4:55 am

    I believe there are few ways of accomplishing this.
    You can specify that course entity is unchanged rather than added, along these lines:

    ctx.Entry(course).State = EntityState.Unchanged;
    

    Or instruct your context, that you are working with existing entity:

    ctx.Courses.Attach(course);
    

    More info here:
    http://msdn.microsoft.com/en-us/data/jj592676.aspx

    EDIT

    There are some running samples from my solution, I verified they work as expected.
    In all cases we have Publisher record in database with ID = 2 and Name = “Addison Wesley” (irrelevant to the example, but just for good measure).

    Approach 1 – Setting Entity State

    using (var context = new Context())
    {
        var book = new Book();
        book.Name = "Service Design Patterns";
        book.Publisher = new Publisher() {Id = 2 }; // Only ID is required
        context.Entry(book.Publisher).State = EntityState.Unchanged;
        context.Books.Add(book);
        context.SaveChanges();
    }
    

    Approach 2 – Using Attach method

    using (var context = new Context())
    {
        var book = new Book();
        book.Name = "Service Design Patterns";                
        book.Publisher = new Publisher() { Id = 2 }; // Only ID is required
        context.Publishers.Attach(book.Publisher);
        context.Books.Add(book);
        context.SaveChanges();
    }
    

    Approach 3 – Setting Foreign Key value

    using (var context = new Context())
    {
         var book = new Book();
         book.Name = "Service Design Patterns";
         book.PublisherId = 2; 
         context.Books.Add(book);
         context.SaveChanges();
    }
    

    For this last approach to work I needed to add extra property PublisherId, it has to be named according to NavigationPropertyName + ‘Id” convention to be picked up by EF auotmatically:

    public int PublisherId { get; set; }
    public Publisher Publisher { get; set; }
    

    I am using here EF5 Code First, but it is very similar to POCO.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am wanting to use jquery to do a show/hide of a DIV from
I'm wanting to use a short url similar to a short url from bit.ly.
I have a Company entity with about 20 fields and I'm wanting to use
I'm in VS2008 with Entity Framework. I'm accessing objects from the database using esql
I am wanting to zip up a list of entities with a new entity
I'm in ASP.NET MVC and am (mostly) using Entity Framework. I want to call
We are wanting to use both NHibernate and Microsoft Sync Framework - has anyone
I'm trying to use Entity Framework 5 Code First. I've created model classes and
I'm looking at a new project and we are wanting to use Flex (to
I'm wanting to use a php variable as the destination email for Amazon SES

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.