Reputation: 813
There are two different models in my project: Movie and Actor. Movie has a list of actors and Actor has a list of movies. What I want to do is given a movie, get all of the actors, and then for each actor examine their movies acted in.
So, to get the information, I use:
var movie = context.Movies.Include("Cast.ActingCredits").FirstOrDefault(m => m.Key == key);
The problem is that while the list ActingCredits
is not null, there are no values in it. Is there something that I am missing to load the values in the list? ActingCredits
is an ICollection<Movie>
.
public class Actor : ModelBase
{
public ICollection<Movie> ActingCredits { get; set; }
}
public class Movie : ModelBase
{
public string Title { get; set; }
public DateTime Year { get; set; }
public Genre Genre { get; set; }
public int RunTime { get; set; }
public int Sales { get; set; }
public ICollection<Actor> Cast { get; set; }
}
EDIT: It has come to my attention that this may be wrong and is the cause of the issue.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Movie>().HasMany(p => p.Cast).WithMany();
modelBuilder.Entity<Actor>().HasMany(m => m.ActingCredits).WithMany();
}
Upvotes: 0
Views: 179
Reputation: 813
The problem was with the database and how I initialized it.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Movie>().HasMany(p => p.Cast).WithMany(p => p.ActingCredits);
modelBuilder.Entity<Actor>().HasMany(m => m.ActingCredits).WithMany(m => m.Cast);
}
Thanks to all who commented. I believe I understand entity framework a whole lot more now.
Upvotes: 1
Reputation: 1871
I suggest adding this:
using System.Data.Entity;
And then you can do the Include with strongly typed variables
var movie = context.Movies.Include(r => r.Cast)
However what I think you really want is to use Select instead of Include?
var movie = context.Movies.Select(r => r.Cast).SelectMany(r => r.ActingCredits);
Upvotes: 0
Reputation: 394
You are not typing the correct name of the property in the include. Try this:
var movie = context.Movies.Include("Cast").FirstOrDefault(m => m.Key == key);
Also, make sure that your database is populated before executing this. I tested this and it works, it retrieves everything.
Upvotes: 1