0

My dbContext always returns null for my junction table. Can I solve the problem by not changing the DB relationship design?

My problem

enter image description here

I want just Id = 1 and Stationery_Id = 1 and UOM_Id = 1

Here is all the detail information...

Database Design

Database design

Class

enter image description here

Data in my db

enter image description here

Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56
Triple K
  • 379
  • 1
  • 3
  • 14
  • Have you implemented the relationships in your code? – Hadi Samadzad Jan 19 '20 at 07:00
  • @Hadi That all my codes.. I don’t know how to do it. – Triple K Jan 19 '20 at 07:07
  • 1
    Check this: [https://www.entityframeworktutorial.net/efcore/configure-many-to-many-relationship-in-ef-core.aspx](https://www.entityframeworktutorial.net/efcore/configure-many-to-many-relationship-in-ef-core.aspx) – Hadi Samadzad Jan 19 '20 at 07:18
  • @Hadi Thank for your support bro. I used model first approach. I can't update `dbContext` and `model class` manually I think. Debug never reach to `onModelCreating` – Triple K Jan 19 '20 at 07:45
  • @Hadi I found `Model first approch` never execute `onModelCreating` https://stackoverflow.com/questions/7876586/ef-4-1-onmodelcreating-not-called – Triple K Jan 19 '20 at 07:50
  • @Hadi Thanks I changed connection string and it executed `onModelCreating` and works. But is there any problem to my `Model First Approach`? I am new to this asp.net MVC – Triple K Jan 19 '20 at 08:09
  • 1
    Isn't it related to lazy loading ?! try using `Include`. follow https://entityframework.net/when-to-use-include – Hamed Moghadasi Jan 19 '20 at 11:35

1 Answers1

1

I think it's related to lazy loading. As this tutorial said:

Lazy loading is delaying the loading of related data until you specifically request for it

You never ever request related data directly in this code snippet, so the expectation of loading related data is wrong.

If you wanna load related data at the moment, you can use Include to achieve that:

db.StockUOMs.Include(i => i.UOM).Include(i => i.Stationery).ToList();

for a deep dive, you can follow this link.

good luck.

Hamed Moghadasi
  • 1,523
  • 2
  • 16
  • 34