Lazy loading properties after an insert

前端 未结 2 1357
粉色の甜心
粉色の甜心 2020-12-18 08:44

I have a parent and child object. If I do the following

Child c = new Child();

c.ParentID = parentID;
context.Child.Add(c);
context.SaveChanges();

int i =         


        
相关标签:
2条回答
  • 2020-12-18 09:11

    A bit late after the question but just to clarify. As MS docs states here, I use this instead:

    using (var context = new BloggingContext())
    {
        var post = context.Posts.Find(2);
    
        // Load the blog related to a given post.
        context.Entry(post).Reference(p => p.Blog).Load();
    
        // Load the blog related to a given post using a string.
        context.Entry(post).Reference("Blog").Load();
    
        var blog = context.Blogs.Find(1);
    
        // Load the posts related to a given blog.
        context.Entry(blog).Collection(p => p.Posts).Load();
    
        // Load the posts related to a given blog
        // using a string to specify the relationship.
        context.Entry(blog).Collection("Posts").Load();
    }
    

    But it will work only if you use the Add() method

    context.Set<T>().Add(post);
    context.SaveChanges();
    context.Entry(post).Reference(p => p.Blog).Load();
    

    it will not work with .AddRange()

    0 讨论(0)
  • 2020-12-18 09:21

    I guess you are working with lazy loading enabled. If you want that the navigation property gets populated after adding the object with the foreign key property to the context you must use the Create method of DbSet (instead of instantiating the object with new):

    Child c = context.Child.Create();
    

    With active lazy loading this will create a proxy object which ensures that the navigation property gets loaded.

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