Entity Framework Detach an entity and the related entities gone

后端 未结 2 1171
轮回少年
轮回少年 2021-01-01 05:18

When I use Entity Framework, I want to query out a record in a context and add it to another context with the same schema, after query out the record, I detach it from the c

2条回答
  •  孤城傲影
    2021-01-01 05:58

    Are you asking how to load the child entities? If so, you can do eager loading with the .Include method. Given a Person class and a PhoneNumber class where Person has a collection of PhoneNumber, you could do the following:

    List People = db.People.Where(p => p.Name = "Henry")
                                   .Include("PhoneNumbers")
                                   .ToList();
    

    Or you can do what is called explicit loading where you load your entities and call the .Load method on the collections of child and related entities that you want to load. Generally you do this when you do not have LazyLoading enabled (and LazyLoading is enabled by default in 4.0+ don't recall in previous versions).

    Regardless of how you query and load them, you will have to detach entities that you want to attach to a different context.

    Here is a link to a pretty good MSDN article on loading entities.

提交回复
热议问题