c# - LINQ 延迟加载和创建新对象

标签 c# entity-framework linq

我有几节课,

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/

相关文章:

c# - StreamWriter 所有行到文件

c# - 使用自定义方法构造 AndAlso/OrElse LINQ 表达式

c# - 具有延迟执行和 SQL 端分组的 EF Core Group By

c# - 使用 where 子句查询 linq

c# - 无法确定类型之间关联的主体端 - Entity Framework 错误,同一类之间的类关系

c# - LINQ to Nhibernate 性能

c# - 是否可以只在 ASP.Net 中处理 404 错误?

c# - 如何使用派生类属性覆盖虚拟基类属性

c# - 如何从 HttpPostedFile 创建字节数组

c# - Visual Studio安装C#组件后无法打开vcxproj