Search code examples
entity-framework-coreentity-relationshipef-core-5.0

ef core - two different relationships for the same tables


I have two tables which have two different relationships:

class Suggestion {
    Guid Id { get; set; }
    
    Guid LastRevisionId { get; set; }
    SuggestionRevision LastRevision { get; set; }

    ICollection<SuggestionRevision> SuggestionRevisions { get; set; }
}

class SuggestionRevision {
    Guid Id { get; set; }
    
    Guid SuggestionId { get; set; }
    Suggestion Suggestion { get; set; }
}

I can have many suggestion revisions for a suggestion. This is one-to-many relationship.

Additionally, I keep another column LastRevision for easy access to the last revision of the suggestion in Entity Framework using Include(), and this is a one-to-one relationship (at least I would like it to be).

I have OnModelCreating as below:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Suggestion>()
        .HasMany(b => b.SuggestionRevisions)
        .WithOne(w => w.Suggestion);

    modelBuilder.Entity<Suggestion>()
        .HasOne(b => b.LastRevision)
        .WithOne()
        .OnDelete(DeleteBehavior.Restrict);
}

However, this did not work. How should I configure this?

Also, keeping the last revision id is a logical design choice? Seems I am missing something...


Solution

  • I have found the answer in this post: Multiple relations between entities in EF Core and my model configuration is as below:

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<SuggestionRevision>()
            .HasOne(b => b.Suggestion)
            .WithMany(w => w.SuggestionRevisions)
            .HasForeignKey(w => w.SuggestionId);
    
        modelBuilder.Entity<Suggestion>()
            .HasOne(b => b.LastRevision)
            .WithOne()
            .HasForeignKey<Suggestion>(w => w.LastRevisionId);
    }
    

    I guess the key point is determining the primary and reference tables.