首页 > 解决方案 > 实体框架代码优先 - 无法使用包含检索嵌套对象

问题描述

我刚刚开始学习实体框架代码优先。我正在尝试使用.Include语法来获取相关对象。我已经能够成功地将对象从一对多关系中检索到列表中,但不能让它从多对一关系中工作。所以我有一首歌,它有一个相关的管弦乐队和一个相关的歌手

对象定义

public class Song
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    [ForeignKey("OrchestraId")]
    public Orchestra Orchestra { get; set; }
    public int OrchestraId { get; set; }
    [ForeignKey("SingerId")]
    public Singer Singer { get; set; }
    public int SingerId { get; set; }
    public int Genre { get; set; }
    public string Year { get; set; }

    public Song()
    {
        this.Orchestra = new Orchestra();
        this.Singer = new Singer();
    }
}

public class Singer
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class Orchestra
{
    public int Id { get; set; }
    public string Name { get; set; }
}

我有一个上下文对象

public class POCContext : DbContext
{
    public DbSet<Singer> Singers { get; set; }
    public DbSet<Orchestra> Orchestras { get; set; }
    public DbSet<Song> Songs { get; set; }
}

我用来获取歌曲的代码如下

    public Song GetSong(int songId)
    {
        Song song = new Song();

        song = _context.Songs.Include(s => s.Orchestra)
            .Include(s => s.Singer)
            .Single(s => s.Id == songId);
        return song;
    }

当我在 return 语句上设置断点并查看歌曲时,会填充歌曲对象,但不会填充歌手或管弦乐队对象。

我在这里查看了以下相关问题,但我无法弄清楚我做错了什么。任何帮助是极大的赞赏。

问候卡尔

标签: c#entity-framework-6

解决方案


管弦乐队和歌手应该是虚拟的。

public virtual Orchestra Orchestra { get; set; }

public virtual Singer Singer { get; set; }

这是一个示例配置:

public class Song
{
    [Key]
    public Guid Id { get; set; }

    public string Title { get; set; }

    //navigation property
    public virtual List<Singer> Singers { get; set; }
}


public class Singer
{
    [Key]
    public int Id { get; set; }

    [ForeignKey("Song")]
    [Required]
    public string SongId { get; set; }

    [Required]
    public string Name { get; set; }

    //navigation property
    public virtual Song Song { get; set; }
}

推荐阅读