Home > OS >  Entity Framework Core: foreign key and reference table Id column do not match
Entity Framework Core: foreign key and reference table Id column do not match

Time:10-13

I'm currently using EF Core 5 for developing. I have an existing database, so changing columns may not be a good option.

For example I got two tables:

public class CalssA
{
    public long AId { get; set; }
    public long TheBId { get; set; }
    [Foreign("TheBId")]
    public virtual ClassB B { get; set; }
}

public class ClassB
{
    public long BId { get; set; }

    [InverseProperty(nameof(CalssA.B))]
    public virtual ICollection<ClassA> Aas {get;set;}
}

When I try to get A data with B, it seems B info is not join to the A.

var a = _AContext.As.Include(a => a.B).FirstOrDefault();
var b = a.B // get null

Is it join issue? How should I specify the column to join with EF Core?

Thanks

CodePudding user response:

you have to add navigation properties


public class ClassA
{  
    [Key]
    public long AId { get; set; }

    public long? TheBId { get; set; }
    [ForeignKey( nameOf(TheBId))]
    [InverseProperty(nameOf(ClassB.Aas))] 
    public virtual ClassB B { get; set; }
}
public class ClassB
{
    [Key]
    public long BId { get; set; }
    
  
      [InverseProperty(nameof(ClassA.B))]
    public virtual ICollection<ClassA>  Aas {get; set;} //one-to-many
}

you can try to add to dbcontext

modelBuilder.Entity<ClassA>(entity =>
            {
                entity.HasOne(d => d.B)
                   .WithMany(p => p.Aas)
                   .HasForeignKey(d => d.TheBId);
                  
            });
  • Related