0

I am using the code-First approach of MVC facing the below issue.

I have 1 The Admin model which has 2 properties that represent a separate class as shown below respectively.

 public class Admin
        { 
            [Key]
            [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
            public int Id { get; set; }
            public string Name { get; set; }
            public List<IdProof> IdProofDocs { get; set; }
            public Subscription subscription { get; set; }
         }

    public class IdProof
        { 
            [Key]
            [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
            public int Id { get; set; }
            public string File { get; set; }
        }
 

    public class Subscription
        {
            [Key]
            [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
            public int Id { get; set; }
            public double TotalAmount { get; set; }
            public double PaidAmount { get; set; }
        }

When I try to save it, it successfully saves values in 3 tables including the last 2 (i.e. IdProof, Subscription) of the Admin Model. see below code

 [HttpPost]
            public ActionResult AddHotel(Admin admin)//saving correctly in 3 table i.e. admin, subscription,IdProof
            { 
                dbContext.Admins.Add(admin);
                dbContext.SaveChanges();
                return RedirectToAction("someActionMethod");
            }   

till now it's good, but from here

when I try to get records by using the below code

 public ActionResult AllAdmins()
        { 
            List<Admin> ListAdmin= dbContext.Admins.ToList();//here its fetching records from admin table only ;(
            return View(ListAdmin);
        }

It gives me only Admin table data, not the other 2 tables*** i.e IdProof & Subscription. I was wondering that EF automatically saves data in the other 2 tables by its model, so at the time of fetching why it's not giving me data from the other 2 tables.

I am using the Code-First approach in mvc5, what is needed to change in my code. I am new in mvc.

Thanks in advance

Satish
  • 37
  • 6

2 Answers2

0

You need to include other tables if you want EF to load it for you.

List<Admin> ListAdmin= dbContext.Admins
    .Include(x => x.IdProofDocs).Include(x => x.Subscription).ToList()
Derviş Kayımbaşıoğlu
  • 24,022
  • 2
  • 42
  • 59
0

EF is having concept of Lazy Loading and Eager Loading.

  1. Lazy Loading In Lazy loading EF not load the related entities until ask for it.

Link: https://www.entityframeworktutorial.net/lazyloading-in-entity-framework.aspx

  1. Eager Loading In Eager Loading, Related Entity mentioned at the Query time using Include method.

Link : https://www.entityframeworktutorial.net/eager-loading-in-entity-framework.aspx

Depend on requirement, you can choose option.

Ravi
  • 302
  • 2
  • 9