Home > Back-end >  EF Core: how to specify foreign key in one-way relationships
EF Core: how to specify foreign key in one-way relationships

Time:03-01

I'm using the Entity Framework Core 6 fluent API to configure my database schema in a .NET Core project.

When declaring two-way relationships we can easily specify the foreign key like this:

modelBuilder.Entity<Foo>()
    .HasMany(x => x.Bars)
    .WithOne(x => x.Foo)
    .HasForeignKey(x => x.FooId);

However, if we have a one-way only relationship like this:

modelBuilder.Entity<Foo>()
    .HasOne(x => x.Bar);

I don't understand how to specify the foreign key, since the .HasOne method does not return an object that has the .HasForeignKey() method.

How do you specify the foreign key in these cases?

CodePudding user response:

Try to do something like this:

  modelBuilder.Entity<Foo>()
            .HasOne(x => x.Bar)
            .WithOne()
            .HasForeignKey(e => e.Whatever);

Also this one maybe can help you too check

  • Related