Entity Framework (EF) Core FluentApi Relationships without Navigation Properties

Entity Framework (EF) Core allows you to define relationships between entities using Fluent API, even without explicitly creating navigation properties. This can be useful when you want to define relationships between entities but don’t want to create navigation properties in your entity classes. Here’s how you can achieve this:

Let’s consider an example where you have two entities: Author and Book, and you want to establish a one-to-many relationship between them without creating navigation properties.

public class Author
{
    public int AuthorId { get; set; }
    public string Name { get; set; }
}

public class Book
{
    public int BookId { get; set; }
    public string Title { get; set; }
    public int AuthorId { get; set; } // Foreign key

    // No navigation property for Author
}

Here’s how you can define the relationship using Fluent API in your DbContext’s OnModelCreating method:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<Book>()
        .HasKey(b => b.BookId);

    modelBuilder.Entity<Author>()
        .HasKey(a => a.AuthorId);

    modelBuilder.Entity<Book>()
        .HasOne<Author>()
        .WithMany() // No navigation property
        .HasForeignKey(b => b.AuthorId)
        .IsRequired();

    // Other configurations...
}

In this example, the WithMany() method is used without specifying a navigation property. This indicates that the Author entity is on the “many” side of the one-to-many relationship with Book, even though there’s no explicit navigation property in the Author class.

With this configuration, you can still perform database operations involving the relationship without creating navigation properties in your entity classes. However, keep in mind that navigation properties are often helpful for querying and easier navigation through relationships in your code.

Remember to adjust the configuration according to your specific entities and relationships. The Fluent API offers flexibility to define relationships based on your application’s needs.