Id匹配上的EF填充导航属性

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

我想在不同班级的List<Dock>时填充Profile.MatchId == Dock.MatchId

这是两个类的精简版:

public class Profile
{
  [Key]
  [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
  public int ProfileId { get; set; }
  public int MatchId { get; set; }

  public virtual List<Dock> Docks { get; set; } = new List<Dock>();
}

public class Dock
{
  [Key]
  [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
  public int DockId { get; set; }
  public int MatchId { get; set; }
}

如何让List<Dock> Docks导航属性正确填充?我相信我需要通过modelBuilder连接它 - 但是之前没有这样做过。

c# entity-framework
2个回答
-1
投票

美好时光!有一个非常简单的模型关系配置示例。

public class SomeContext : DbContext
{
    public DbSet<Profile> Profiles { get; set; }
    public DbSet<Dock> Docks { get; set; }

    protected override Void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        builder.Entity<Dock>()
            .HasOne(x => x.Profile)
            .WithMany(x => x.Docks)
            .HasForeignKey(x => x.ProfileId);
    }
}




public class Profile
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ProfileId { get; set; }
    public int MatchId { get; set; }

    public virtual List<Dock> Docks { get; set; } = new List<Dock>();
}

public class Dock
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int DockId { get; set; }
    public int MatchId { get; set; }

    public int ProfileId { get; set; }
    public Profile Profile { get; set; }
}

-1
投票

实际上,由于Profile和Docks之间没有直接连接,因此无法在Profile中获取List <> Docks的值。

你可以试试这个。

public class Profile
{
  [Key]
  [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
  public int ProfileId { get; set; }

  public virtual List<Dock> Docks { get; set; } = new List<Dock>();
}

public class Dock
{
  [Key]
  [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
  public int DockId { get; set; }

  [ForeignKey("Profile")]
  public int ProfileId { get; set; }
  public Profile Profile {get; set; }
} 
© www.soinside.com 2019 - 2024. All rights reserved.