I have an entity that have a one to one relationship with itself:
public class Link
{
public long Id { get; set; }
public long OtherLinkId { get; set; }
public Link OtherLink { get; set; }
}
How can I define this relationship with fluent API?
My solution:
modelBuilder.Entity<Link>()
.HasOne(x => x.OtherLink)
.WithOne(x => x.OtherLink)
.OnDelete(DeleteBehavior.Restrict);
but on migration, it tries to create a second OtherLink
.
You can achieve this by using a nullable ForeignKey
attribute in your model class.
public class Link
{
public long Id { get; set; }
public long? OtherLinkId { get; set; } = null;
[ForeignKey("OtherLinkId")]
public Link OtherLink { get; set; }
}