简体   繁体   中英

What is the proper way to have unary relationship in EF-core code first?

I have a Destination Entity, Which I made unary because a destination can have another destination. Eg Point A -> Point B -> Point C

I have tried creating the appropriate Entity class.

    public class Destination
    {
        public int DestinationId { get; set; }
        public Destination NextDestination { get; set; }
        public float Distance { get; set; }
        public DateTime ExpectedArrival { get; set; }
        public DateTime ActualArrival { get; set; }
    }

There were no errors but what i get instead is

Destination
NextDestinationDestinationId
Distance
ExpectedArrival
ActualArrival

Is there anyway that I can make it like to call it like "Destination.NextDestinationId"

public class Destination
    {
        public int DestinationId { get; set; }
        public int PreviousDestinationId { get; set; }

        public virtual Destination Previous { get; set; }
        public virtual Destination Next{ get; set; }
    }

    public class DestinationConfiguration : IEntityTypeConfiguration<Destination>
    {
        public void Configure(EntityTypeBuilder<Destination> builder)
        {
            builder
                .HasOne(p => p.Previous)
                .WithOne(p => p.Next)
                .HasForeignKey(p => p.PreviousDestinationId)
                .OnDelete(DeleteBehavior.Restrict);

        }
    }

You can configure custom foreign key name in fluent API:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{

    modelBuilder.Entity<Destination>()
     .HasRequired(w => w.Destination)
     .WithMany()
     .Map(m => m.MapKey("NextDestinationId"));
}

This will name your column "NextDestinationId" instead of "NextDestinationDestinationId".

I don't know if you need .WithMany() or something else in configuration, that's up to you.

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