使用 LINQ 映射到 DTO 时出现问题
Trouble mapping to DTOs with LINQ
我最近一直在使用 DTO,无法确定此代码存在的问题。
我正在将流派名称和电影名称映射到 GenreMovieDto。 Visual Studio 没有显示任何错误(红线等),但是当代码为 运行 时,我得到以下信息:
- $异常{"The specified type member 'Movies' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported."}System.NotSupportedException
我的代码如下:
public class Genre
{
public int Id { get; set; }
public string Name { get; set; }
public IEnumerable<Movie> Movies { get; set; }
}
public class Movie
{
public int Id { get; set; }
public string Name { get; set; }
public string AgeRating { get; set; }
public int NumberInStock { get; set; }
public Genre Genre { get; set; }
}
public class GenreMovieDto
{
public string GenreName { get; set; }
public IEnumerable<Movie> Movies { get; set; }
}
还有我的 API 电话:
public IEnumerable<GenreMovieDto> GetGenresWithMovies()
{
var genresWithMovies = _context.Genres
.Include(m => m.Movies)
.Select(x => new GenreMovieDto
{
GenreName = x.Name,
Movies = x.Movies <<<<< CRASHES HERE
})
.ToList();
return genresWithMovies;
}
有什么想法吗?欢迎任何和所有的建议/批评:P 我是来学习的。
提前致谢
你可以这样做(EF 不支持 IEnumerable<...> 类型的成员):
public class Genre
{
public int Id { get; set; }
public string Name { get; set; }
public virtual List<Movie> Movies { get; set; }
}
我最近一直在使用 DTO,无法确定此代码存在的问题。
我正在将流派名称和电影名称映射到 GenreMovieDto。 Visual Studio 没有显示任何错误(红线等),但是当代码为 运行 时,我得到以下信息:
- $异常{"The specified type member 'Movies' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported."}System.NotSupportedException
我的代码如下:
public class Genre
{
public int Id { get; set; }
public string Name { get; set; }
public IEnumerable<Movie> Movies { get; set; }
}
public class Movie
{
public int Id { get; set; }
public string Name { get; set; }
public string AgeRating { get; set; }
public int NumberInStock { get; set; }
public Genre Genre { get; set; }
}
public class GenreMovieDto
{
public string GenreName { get; set; }
public IEnumerable<Movie> Movies { get; set; }
}
还有我的 API 电话:
public IEnumerable<GenreMovieDto> GetGenresWithMovies()
{
var genresWithMovies = _context.Genres
.Include(m => m.Movies)
.Select(x => new GenreMovieDto
{
GenreName = x.Name,
Movies = x.Movies <<<<< CRASHES HERE
})
.ToList();
return genresWithMovies;
}
有什么想法吗?欢迎任何和所有的建议/批评:P 我是来学习的。
提前致谢
你可以这样做(EF 不支持 IEnumerable<...> 类型的成员):
public class Genre
{
public int Id { get; set; }
public string Name { get; set; }
public virtual List<Movie> Movies { get; set; }
}