导航属性不返回完整的实体集

时间:2018-04-12 14:54:44

标签: c# entity-framework-6

这是我的实体的简化模型

  public class Location
  {
    [Key]
    [StringLength(8)]
    public string Code { get; set; }

    [Required]
    [StringLength(100)]
    public string FriendlyName { get; set; }

    public virtual ICollection<Move> Moves { get; set; }
}

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

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

    [Required]
    [StringLength(8)]
    public string LocationFromCode { get; set; }

    [Required]
    [StringLength(8)]
    public string LocationToCode { get; set; }

    [ForeignKey("LocationFromCode")]
    public Location LocationFrom { get; set; }

    [ForeignKey("LocationToCode")]
    public Location LocationTo { get; set; }

}

为了避免循环引用问题,我在我的上下文中实现了以下逻辑

   protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Location>()
                .HasMany(l => l.Moves)
                .WithRequired(m => t.LocationFrom)
                .WillCascadeOnDelete(false);

            modelBuilder.Entity<Location>()
                .HasMany(a => a.Moves)
                .WithRequired(t => t.LocationTo)
                .WillCascadeOnDelete(false);

        }

我遇到的问题是我只能通过Location.Moves看到那些正在使用LocationTo-&gt;位置约束的移动

是EF限制还是我做错了?

1 个答案:

答案 0 :(得分:0)

public class Location
  {
    [Key]
    [StringLength(8)]
    public string Code { get; set; }

    [Required]
    [StringLength(100)]
    public string FriendlyName { get; set; }

    public virtual ICollection<Move> MovesTo { get; set; }
    public virtual ICollection<Move> MovesFrom { get; set; }

}

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

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

    [Required]
    [StringLength(8)]
    public string LocationFromCode { get; set; }

    [Required]
    [StringLength(8)]
    public string LocationToCode { get; set; }

    [ForeignKey("LocationFromCode")]
    [InverseProperty("MovesFrom")]
    public Location LocationFrom { get; set; }

    [ForeignKey("LocationToCode")]
    [InverseProperty("MovesTo")]
    public Location LocationTo { get; set; }

}

to avoid a cyclical reference issue:

   protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Location>()
                .HasMany(l => l.MovesFrom)
                .WithRequired(m => t.LocationFrom)
                .WillCascadeOnDelete(false);

            modelBuilder.Entity<Location>()
                .HasMany(a => a.MovesTo)
                .WithRequired(t => t.LocationTo)
                .WillCascadeOnDelete(false);

        }