EF核心关系未带回相关记录

问题描述 投票:0回答:1

我正在使用 .NET Entity Framework 8.0.1

我有 3 个课程 - 景点、地址和广告 Attraction 和 Advert 之间存在一对多关系 以及景点和地址之间的 1 对 1 关系 我已经使用迁移创建了数据库。

这是我的课程:

public class Attraction : BaseEntity
{
    [Required]
    [MaxLength(100)]
    public string Name { get; set; }

    [Required]
    [MaxLength(100)]
    public string Website { get; set; }

    public Address Address { get; set; }

    public ICollection<Advert> Adverts { get; } = new List<Advert>();

    public Attraction()
    {
    }

}

public class Address : BaseEntity
{
    [Required]
    public Guid AttractionId { get; set; }

    [Required]
    [MaxLength(100)]
    public string Line1 { get; set; }

    [Required]
    [MaxLength(100)]
    public string Line2 { get; set; }

    [Required]
    [MaxLength(100)]
    public string Line3 { get; set; }

    [Required]
    [MaxLength(100)]
    public string Line4 { get; set; }

    [Required]
    [MaxLength(100)]
    public string Line5 { get; set; }

    [Required]
    [MaxLength(16)]
    public string PostCode { get; set; }

    public Address()
    {
    }
}

public class Advert : BaseEntity
{
    [Required]
    public Guid AttractionId { get; set; }

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

    [Required]
    public DateTime DisplayFrom { get; set; }

    [Required]
    public DateTime DisplayTo { get; set; }

    [Required]
    public int DisplayType { get; set; }

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

    public Advert()
    {
    }

}

它们派生自的基实体类:

public class BaseEntity
{

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Required]
    public Guid Id { get; set; }

}

在应用程序 DBContext 类中,我设置了如下关系:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{          
    modelBuilder.Entity<Attraction>()
        .HasMany(e => e.Adverts)
        .WithOne()
        .HasForeignKey(e => e.AttractionId);

    modelBuilder.Entity<Attraction>()
        .HasOne(e => e.Address)
        .WithOne()
        .HasForeignKey<Address>(e => e.AttractionId);
}

当我运行选择查询来检索景点类时,地址始终为空,广告列表始终为空。

这是我的询问

public async Task<List<Attraction>> SelectAll()
{
    return await Task.Run(() => AppDbContext.Attractions.ToList());
}
c# entity-framework-core relation
1个回答
0
投票

当您不使用延迟加载时,您必须在查询中包含相关实体。

您可以使用

.Include(x => x.Adverts).ThenInclude(x => x.Address)
方法来执行此操作以包含两个导航。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.