As you know in Entity Framework Core 5 has the possibility to create a Many-to-Many relationship without explicitly mapping the join table. I have followed This Example and build successfully as described with this following model:
public class Movie
{
public int MovieId { get; set; }
public string Name{ get; set; }
public List<Genre> Genres { get; set; }
}
public class Genre
{
public int GenreId { get; set; }
public string GenreName { get; set; }
public List<Movie> Movies{ get; set; }
}
This is OnModelCreating
:
public class MyEntityContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder opBuilder)
{
opBuilder.UseSqlServer("Data Source=(localdb)\\ProjectsV13;Initial Catalog=MyContextDB;");
}
public DbSet<Movie> Movies { get; set; }
public DbSet<Genre> Genres { get; set; }
}
then inserted some movie and genres:
using (var context = new MyEntityContext())
{
context.Database.EnsureCreated();
var comedy = new Genre() { GenreName = "Comedy" };
var action = new Genre() { GenreName = "Action" };
var horror = new Genre() { GenreName = "Horror" };
var scifi = new Genre() { GenreName = "Sci-fi" };
context.AddRange(
new Movie() { Name = "Avengers", Genres = new List<Genre>() { action, scifi } },
new Movie() { Name = "Satanic Panic", Genres = new List<Genre>() { comedy, horror } });
context.SaveChanges();
}
I'm adding some code after context.SaveChanges();
:
var ReadMovie = context.Movies.ToList();
foreach (var movie in ReadMovie)
{
var genres = String.Join(",",movie.Genres.Select(s => s.GenreName).ToArray());
Debug.Print(String.Format("Move: {0}, Genres: {1}", movie.Name, genres));
}
This is the error I'm facing that says movie.Genres
is null
:
System.ArgumentNullException: 'Value cannot be null. (Parameter 'source')'
I've already added new List<Genre>()
while insertion, didn't I?
ReadMovie is containing only MovieId and Name, the List is null... the way that I know is creating a View which is joining Movies and Genres and there you can fill List the other way is:
var ReadMovie = context.Movies.Include(t=>t.Genres).FirstOrDefaultAsync(t => t.MovieId== id).ToList();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.