[英]EF Core 5 Retrieve database Many-to-Many record 'Value cannot be null. (Parameter 'source')'
As you know in Entity Framework Core 5 has the possibility to create a Many-to-Many relationship without explicitly mapping the join table.如您所知,在 Entity Framework Core 5 中,无需显式映射连接表即可创建多对多关系。 I have followed This Example and build successfully as described with this following model:我已按照此示例并按照以下 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
:这是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();
我在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
:这是我面临的错误,说movie.Genres
是null
:
System.ArgumentNullException: 'Value cannot be null. System.ArgumentNullException: '值不能是 null。 (Parameter 'source')' (参数'源')'
I've already added new List<Genre>()
while insertion, didn't I?我已经在插入时添加了new List<Genre>()
,不是吗?
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: ReadMovie 仅包含 MovieId 和 Name,列表为 null ...我知道的方式是创建一个加入电影和流派的视图,您可以在其中填写列表,另一种方式是:
var ReadMovie = context.Movies.Include(t=>t.Genres).FirstOrDefaultAsync(t => t.MovieId== id).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.