SQL Server How to populate a many-to-many relationship in ASP.NET Core model

ev7lccsx  于 2023-03-28  发布在  .NET
关注(0)|答案(1)|浏览(94)

I have an ASP.NET Core app when I tried to pull the models from the database using the Scaffold-DbContext command, it pulled most of the tables, and added all relationships between them.

Except one table that basically have all passengers ids mapped to their registered trip ids. So I managed to find a way to inform Entity Framework to add the table like that:

public partial class Ticket
{
    public int PassengerId { get; set; }
    public int TripId { get; set; }
    public virtual Passenger Passenger { get; set; } = null!;
    public virtual Trip Trip { get; set; } = null!;
}

Then in the context class it has defined how the table is mapped to the class:

modelBuilder.Entity<Ticket>(entity =>
        {
            entity.HasKey(e => new { e.PassengerId, e.TripId })
                .HasName("PK_Key");
            entity.ToTable("ticket");
            entity.Property(e => e.PassengerId).HasColumnName("passenger_id");
            entity.Property(e => e.TripId).HasColumnName("trip_id");
            entity.HasOne(d => d.Passenger)
                .WithMany(p => p.Tickets)
                .HasForeignKey(d => d.PassengerId)
                .OnDelete(DeleteBehavior.ClientSetNull)
                .HasConstraintName("FK_Ticket_Passenger");
            entity.HasOne(d => d.Trip)
                .WithMany(p => p.Tickets)
                .HasForeignKey(d => d.TripId)
                .OnDelete(DeleteBehavior.ClientSetNull)
                .HasConstraintName("FK_Ticket_Trip");
        });

Now when I run the application, a single ticket object is populated with the two ids as in the actual database but for the Trip object and Passenger object it stores null instead (snipped in the JSON format):

{ "PassengerId": 1, "TripId": 1, "Passenger": null, "Trip": null }

Can someone help figure out what causes the trip and passenger not to store a reference for the object in the database?

zkure5ic

zkure5ic1#

You can include related data from multiple relationships in a single query.Try :

public IActionResult Index()
{
    var ccc = _context.Ticket 
                      .Include(x => x.Passenger)
                      .Include(y => y.Trip)
                      .ToList();
    return Ok(ccc);
}

Read Include to know more.

相关问题