Entity Framework - Eagerly load object graph using stored procedures

前端 未结 3 1139
情歌与酒
情歌与酒 2021-02-06 10:11

Background

I am changing my LINQ-to-SQL code in my project to Entity Framework. Most of the change over was relatively simple, however, I have run into

3条回答
  •  难免孤独
    2021-02-06 10:32

    Okay, so after even further deliberation, I figured out a solution that works for what I am wanting. Since I am in a web environment and have no need to lazily load objects, I turned EnableLazyLoading to false for the entire DbContext. Then, using an EF feature called the magical relationship fix-up, I am able to do the following:

    ViewModel.Model = MyDbContext.usp_ModelA_GetByID(AId).Single();
    var Details = 
    (from b in MyDbContext.usp_ModelB_GetByID(BId)
    join c in MyDbContext.usp_ModelC_GetAll()
       on b.CId equals c.CId
    select new ModelB()
    {
        BId = b.BId,
        CId = b.CId,
        C = c
    }).ToList();  
    //ToList() executes the proc and projects the plate details into the object 
    //graph which never tries to select from the database because LazyLoadingEnabled is
    //false.  Then, the magical relationship fix-up allows me to traverse my object graph
    //using ViewModel.Model.ModelBs which returns all of the ModelBs loaded into the graph
    //that are related to my ModelA.
    

提交回复
热议问题