locked
After Inserting a data to the Database Table the Navigation properties are null RRS feed

  • Question

  • Hi!

    When I am inserting data into the table using Entity Framework and while retrieving the data the Navigation property is null.

    Eg. I have a table called Inventory and it has a Navigation properties called Type and Status.

    without <g class="gr_ gr_23 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar multiReplace" data-gr-id="23" id="23">disposing</g> the DbContext I am retrieving the data by passing the id.

    at this point, the status and type models are null thought it has data.

    Inventory: Inv_id Inv_nme type_id status_id

    when i say : inventory.type.type_name

    I am getting an error saying: <g class="gr_ gr_31 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins doubleReplace replaceWithoutSep" data-gr-id="31" id="31">null</g> instance of an object.

    To avoid the issue temporarily Eager Loading method using Include to call the submodels:

    By using lazy load how can I get the navigation properties data like  :

    inventory.type.type_name

    inventory.status.status_name


    • Edited by Ahmed Malik Monday, December 4, 2017 6:38 AM
    Monday, December 4, 2017 6:30 AM

All replies

  • https://stackoverflow.com/questions/37958053/reload-all-related-objects-navigation-properties-with-entity-framework-dbconte

    try it see wharf happens...

    Monday, December 4, 2017 12:08 PM
  • Hi Ahmed Malik,

    >>By using lazy load how can I get the navigation properties data like:

    Please refer to the following sample, you could get the navigation properties data via LINQ.

    using (var db = new EFDemoContext())
    {
         Inventory inventory = new Inventory() { InventoryName = "Test" };
         Type type = new Type() { TypeId = 1, Type_Name = "T1" };
         Status status = new Status() { StatusId = 1, Status_Name = "S1" };
    
         inventory.Types.Add(type);
         inventory.Status.Add(status);
    
         db.Inventories.Add(inventory);
         db.SaveChanges();
    
         var inver = db.Inventories.Find(1);
         var typeNames = inver.Types.Select(t => t.Type_Name).ToList();
         var statusName = inver.Status.Select(t => t.Status_Name).ToList();
    }

    Best regards,

    Zhanglong Wu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, December 5, 2017 2:01 AM