简体   繁体   中英

How to configure one-to-many relationship with navigation property only on one side (on collection side) with EF Core 5?

Lets say we have Airport and Runway classes: have perfectly fine one-to-many relationship between two tables: Play and Player:

public class Airport
{
    public int Id { get; set; }
    public string Name { get; set; }

    public virtual IList<Runway> Runways { get; set; }
}

public class Runway
{
    public int Id { get; set; }    
    public string Name { get; set; }
    //public int AirportId { get; set; } <- I don't need it!!!
}

My goal is to omit navigation property on Runway side (I don't need a link to Airport here).

But when I use dotnet-ef migrations add InitialCreate command - an AirportId field is created in database for Runway table. How to configure one-to-many relationship with navigation property only on one side (on collection side) with EF Core 5?

There is similar question but for navigation property on a collection side.

I've tried the following with no success (nothing changes):

modelBuilder.Entity<Airport>()
.HasMany<Runway>(a => a.Runways)
.WithOne()
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();

A foreign key column is the central concept of having a functional one-to-many relationship. The database needs it to identify which child entity ( Runway ) belongs to which parent entity ( Airport ). Therefore, you cannot avoid it.

If you don't want the AirportId and the Airport reference in your Runway class you can safely remove them and use the models as -

public class Airport
{
    public int Id { get; set; }
    public string Name { get; set; }

    public virtual IList<Runway> Runways { get; set; }
}

public class Runway
{
    public int Id { get; set; }    
    public string Name { get; set; }
}

You can even remove the relation configuration code as well. EF will automatically create a nullable foreign key column AirportId in the Runway table and use it as a Shadow property (which you cannot access) behind the scene to manage the relationship.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM