My first tip is to change the properties of your collection to ICollection<T> instead of List<T> . You can find a really good explanation in this post .
Now, returning to your real problem, I will make your request:
public List<Post> GetPostsByTadId(int tagId) { using(var context=new MyContext()) { return context.PostTags.Include(p=>p.Post) .Where(pt=> pt.TagId == tagId) .Select(pt=>pt.Post) .ToList(); } }
You will need to load the Post navigation property because EF7 does not support lazy loading, and also, as @Igor recommended in your solution, you have to include PostTags as DbSet in your context:
public DbSet<PostTags> PostTags { get; set; }
Explanation:
Your query starts in the PostTags table, because it is in this table where you can find all the messages associated with a specific tag. See Include as an internal join to the Post table. If you use the connection between the PostTags and Posts filters using TagId , you will get the columns you need. With a Select call, you say that you only need columns from the Post table.
If you remove the Include call, it should still work. With Include you explicitly indicate that you need to make the connection, but with Select Linq EF provider is smart enough to see that it needs to implicitly use the connection to get the Posts columns as a result.
source share