EF Core Foreign Key via Fluent API

c# ef-core-2.0 ef-core-2.1 entity-framework-core

Question

I have a 2 classes:

public class Item
{
    public int Id { get; set; }
    public string ItemName { get; set; }
}
public class ItemStats //inhenrit from Item
{        
    public int Id { get; set; }
    public int MaxEnhanceLevel { get; set; }

    public Item Item { get; set; }
}

This is a TPT but since it's not supported out of the box I can't use inheritance. I know how to achieve this using data annotation

 [ForeignKey(nameof(Item))]
 public int Id { get; set; }

But how can I do this via FluentAPI? I don't want data annotation in my Entitie Classes.

1
1
11/9/2018 8:04:48 PM

Accepted Answer

What you have is a One-to-one relationship with single navigation property, principal entity Item and dependent entity ItemStats, using the so called shared primary key association, where the dependent entity PK is also a FK to the principal entity.

Fluent API for one-to-one relationships are HasOne, WithOne, HasForeignKey and HasPrincipalKey. Please note that the generic type arguments to HasForeignKey and HasPrincipalKey (which normally are omitted for one-to-many relationship) here are important because they indentify which entity is principal and which - dependent.

With that being said, the fluent configuration for your model is:

modelBuilder.Entity<ItemStats>()
    .HasOne(e => e.Item)
    .WithOne()
    .HasForeignKey<ItemStats>(e => e.Id);
1
11/9/2018 8:03:08 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow