I have two entities User
and Profile
. Each of those entities inherits from an Entity
class which contains an Id
property. The relation between the User and the Profile are One-To-One relation. I am trying to use the same Id created for the User entity to be the Id for the Profile entity, i.e. User.Id == Profile.Id
.
I have been trying to do this with FluentAPI but i am unable to. I have read this question and also read this post, but i am still unable to find a solution to my problem.
Here is the code for my entities:
public class Entity<TKey> : IEntity
{
/// <summary>
/// Unique identifier for this entity.
/// </summary>
public virtual int Id { get; set; }
}
public class User : Entity<int>
{
public virtual Profile ProfileItem { get; set; }
}
public class Profile : Entity<int>
{
}
Here are my trials so far, in which all failed:
This mapping generated a
ProfileItemId
in theUser
table:modelBuilder.Entity<User>().HasOne(u => u.ProfileItem) .WithOne() .HasForeignKey<Profile>(p => p.Id) .IsRequired() .OnDelete(DeleteBehavior.Cascade);
I tried adding an inverse navigation property in the
Profile
entity forUser
. TheUser
table was mapped correctly, but aUserId
column was added to theProfile
table:modeBuilder.Entity<User>().HasOne(u => u.ProfileItem) .WithOne(u => u.User) .HasForeignKey<Profile>(p => p.Id) .IsRequired() .OnDelete(DeleteBehavior.Cascade);
The only solution for this problem as reported in the question that i mentioned earlier, is that you have to add an inverse property and then use Data Annotations. I tried the following and it worked:
public class Entity<TKey> : IEntity
{
/// <summary>
/// Unique identifier for this entity.
/// </summary>
public virtual int Id { get; set; }
}
public class User : Entity<int>
{
[InverseProperty("User")]
public virtual Profile ProfileItem { get; set; }
}
public class Profile : Entity<int>
{
[ForeignKey("Id")]
public virtual User User { get; set; }
}
How to get the same to work with FluentAPI?