Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

EF Core: how to specify foreign key in one-way relationships

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading