实体框架关系映射不起作用

时间:2017-11-25 04:34:28

标签: entity-framework asp.net-core .net-core

打印(" Hello World!");

我是.NET世界的初学者,我试图使用实体框架,但我遇到了问题,我的关系实体没有加载,我跟着微软文档但是。

以下是我的模特:

[Table("Path")]
public class Path
{
    [Key]
    public int PathId { get; set; }
    [Required]
    public string Title { get; set; }
    public List<Image> Images { get; set; }
    [Required]
    public string Description { get; set; }
    [Required]
    public float LocationX { get; set; }
    [Required]
    public float LocationY { get; set; }
    [Required]
    public string QrCode { get; set; }
    public List<Mark> Marks { get; set; }
}

[Table("Mark")]
public class Mark
{
    [Key]
    public int MarkId { get; set; }
    public int Value { get; set; }
    public int PathForeignKey { get; set; }
    [ForeignKey("PathForeignKey")]
    public Path Path { get; set; }
}

[Table("Image")]
public class Image
{
    [Key]
    public int ImageId { get; set; }
    [Required]
    public string Name { get; set; }
    public string Description { get; set; }
    public int PathForeignKey { get; set; }
    [ForeignKey("PathForeignKey")]
    public Path Path { get; set; }
    [Required]
    public string Source { get; set; }
}

对我来说,一切都很好,我甚至在我的数据库中输入了正确的条目: database entries

但是当我将数据库读入我的控制器时,我的关系不会加载。

[HttpGet]
public IEnumerable<Path> GetAll()
{
    return _context.Paths.ToList();
}

results

对不起,我想这可能是一个愚蠢的初学者错误,但我不知道我做错了什么。我试过各种数据库系统,虚拟或不...

1 个答案:

答案 0 :(得分:2)

将导航属性标记为virtual。例如:

[Table("Mark")]
public class Mark
{
    [Key]
    public int MarkId { get; set; }
    public int Value { get; set; }
    public int PathForeignKey { get; set; }
    [ForeignKey("PathForeignKey")]
    public virtual Path Path { get; set; }  //Added virtual keyword
}

和加载导航属性的第二种方法是在获取数据时使用Include

return _context.Marks.Include(x => x.Path).ToList();