我有几节课,
public class Album
{
public int AlbumId { get; set; }
public string Title { get; set; }
public Genre genre { get; set; }
public virtual Artist artist { get; set; }
}
public class Artist
{
public int ArtistId { get; set; }
public string Name { get; set; }
public virtual ICollection<Album> albums { get; set; }
}
public class ArtistResponse
{
public int ArtistId { get; set; }
public string Name { get; set; }
}
public class AlbumResponse
{
public int AlbumId { get; set; }
public string Title { get; set; }
public Genre genre { get; set; }
public ArtistResponse artist { get; set; }
}
我正在尝试下载所有带有艺术家的专辑,并使用 AlbumResponse 将其返回。 我有一个 LINQ 表达式
return ctx.Albums.Include(i => i.artist).Select(i => new AlbumResponse
{
AlbumId = i.AlbumId,
artist = new ArtistResponse { Name=i.artist.Name, ArtistId=i.artist.ArtistId},
genre = i.genre,
Title = i.Title
}).ToList();
因此,我通过“Include()”包括“艺术家”,然后在我创建新的 ArtistResponse 的地方创建新的 AlbumResponse。不幸的是,它不起作用。它抛出 InvalidOperationException。 “i.artist.ArtistId”为空,我不知道为什么,没有 ArtistId 初始化一切正常,只有“Name=i.artist.Name”完美。
如何将 ArtistId 附加到“AlbumResponse”中的“艺术家”? 异常:“转换为值类型‘System.Int32’失败,因为物化值为 null。结果类型的泛型参数或查询必须使用可空类型” Album 和 Artist 类在数据库中,AlbumId 和 ArtistId 不可为空。 ArtistResponse 和 AlbumResponse 只是用于添加或从数据库获取信息的“额外”类,因此“*Response”中的 ArtistId 和 AlbumId 只是整数
最佳答案
如果ArtistId
artist
的专栏导航属性是 Nullable<int>
和 ArtistId
的类型ArtistResponse
的属性(property)类型是 int
您应该检查是否有返回值:
return ctx.Albums.Include(i => i.artist).Select(i => new AlbumResponse
{
AlbumId = i.AlbumId,
artist = new ArtistResponse { Name = (i.artist != null) ? i.artist.Name : string.Empty, ArtistId = (i.artist != null && i.artist.ArtistId.HasValue) ? artist.ArtistId.Value : 0 },
genre = i.genre,
Title = i.Title
}).ToList();
这显然只是一个猜测,因为您没有发布类型的定义,也没有发布您收到的实际错误消息。
编辑:
如果更改 ArtistId
的类型会怎样? ArtistResponse
的属性(property)输入 Nullable<int>
( int?
):
public class ArtistResponse
{
public Nullable<int> ArtistId { get; set; }
public string Name { get; set; }
}
关于c# - LINQ 延迟加载和创建新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42164108/