Entity Framework Core 2 one to one relationship "on one table"

c# ef-core-2.0 ef-fluent-api entity-framework-core

Question

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.

1
2
6/24/2018 4:53:37 PM

Popular Answer

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; }
}
2
6/24/2018 5:51:20 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