Entity Framework: adding existing child POCO to new Parent POCO, creates new child in DB

前端 未结 3 1120
北恋
北恋 2020-12-09 22:33

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

相关标签:
3条回答
  • 2020-12-09 22:34

    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 讨论(0)
  • 2020-12-09 22:54

    I also tried the second option it worked for me. I did like the parent->child relationship happening at an object level first and save to db. Maybe I should just remove all the relationships between the entities that EF generates and manually control this myself.

    0 讨论(0)
  • 2020-12-09 22:55

    Entity Framework does not allow relationships that cross contexts.

    If you place the reading of the course and connecting the course to the student within the same using statement, it would work.

    0 讨论(0)
提交回复
热议问题