How to navigate many-to-many relationships in entity framework core

asp.net-core-mvc entity-framework-core

Question

According to Microsoft Docs https://docs.microsoft.com/en-us/ef/core/modeling/relationships#other-relationship-patterns

Many-to-many relationships without an entity class to represent the join table are not yet supported.

Ok, this leads to a nightmare when you need to migrate apps with several many-to-many relationships that were handled perfectly by EF5.

Now I have Keyword, Tag and KeywordTag entities set up as described in the link.

If I have a keyword entity, which is the correct syntax to retrieve all tags associated with such keyword?

In EF5 it was

var kwd = _context.Keywords.Find(my_kwd_id);
var tagList = kwd.Tags;

Which is the equivalent with EF Core? Intellisense allows me to write

kwd.KeywordTags 

but not

kwd.KeywordTags.Tags

...so I cannot find how to access Tags in any way... Please don't tell me that i have to explicitly search then loop the KeywordTag entity to extract Tags ...

1
2
4/29/2017 3:33:58 PM

Popular Answer

Since EF Core does not have exact parity with older versions of EF, you need to write bit different code. You would need to do what @Ivan suggested in comments. You also need to eager load your collection because lazy loading is not available. That means you need to do database query explicitly.

Method 1: Instead of using Find you query database directly and bring in related data. (kwd/tagList) would have same data as you are seeing in EF5.

var kwd = db.Keywords.Include(k => k.KeywordTags)
    .ThenInclude(kt => kt.Tag)
    .FirstOrDefault(k => k.Id == my_kwd_id);
var tagList = kwd.KeywordTags.Select(kt => kt.Tag).ToList();

Alternatively, you can use find but load navigations explicitly. This is somewhat similar to lazy loading but since it is not available you ask EF to load navigations. This will have really bad perf as you will send 1 query to fetch all entries from join table & then 1 query for each related tag in tags table. If you are interested in knowing the way to write it, I can post code for that too.

2
5/9/2017 8:05:12 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow