Johnson Duru
Johnson Duru

Reputation: 682

how to read data from junction table code first approach

how can I retrieve data from junction table in Code first approach.i know i can add data like this.

 Movie.Tag.Add(item)

but want to know how to get back those data in the junction table

Upvotes: 0

Views: 895

Answers (1)

Slauma
Slauma

Reputation: 177133

This gives you all rows in the junction table - each row is represented as an anonymous object with the two Ids of the row as properties:

var junctionTableDataList = (from m in context.Movies
                             from t in m.Tags
                             select new
                             {
                                 MovieId = m.MovieId,
                                 TagId = t.TagId
                             }).ToList();

You can add a where clause before the select if you want to limit the result to a specific or a few movies.

Edit

The same with extension methods and lambda expressions would look like this:

var junctionTableDataList = context.Movies
    .SelectMany(m => m.Tags.Select(t => new
    {
        MovieId = m.MovieId,
        TagId = t.TagId
    }))
    .ToList();

Edit 2

If you want return the data from a method you can create a litte helper type and return a list of those "named" objects instead of anonymous objects:

public class JunctionData
{
    public int MovieId { get; set; }
    public int TagId { get; set; }
}

List<JunctionData> junctionTableDataList
    = (from m in context.Movies
       from t in m.Tags
       select new JunctionData
       {
           MovieId = m.MovieId,
           TagId = t.TagId
       }).ToList();

Or ...Select(t => new JunctionData... for the extension method syntax.

Upvotes: 1

Related Questions