Reputation: 137
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.
Upvotes: 2
Views: 2766
Reputation: 205529
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);
Upvotes: 2