wertzui
wertzui

Reputation: 5720

EF Core One to one relation where both sides are optional but one property is not nullable

I have a model that looks like this:

public class Foo
{
    public long Id { get; set; }
    public long? BarId { get; set; }
    public virtual Bar? Bar { get; set; }
}

public class Bar
{
    public long Id { get; set; }
    public virtual Foo? Foo { get; set;}
    
    // This would be easy, but I want a one to one relation
    // public virtual ICollection<Foo> Foos { get; set; } = new HashSet<Foo>();
}

I now want to configure a one to one relationship. The tricky part is that Bar.Id may have a value that is not present in the Foo.BarId column.

So this must be possible

Foo

Id BarId
1 3
2 null

Bar

Id
3
4 (no Foo.BarId that matches)

How can I achieve this using DataAnnotations or Fluent configuration?

Upvotes: 0

Views: 559

Answers (1)

Serge
Serge

Reputation: 43870

just try this

public class Foo
{
    [Key]
    public long Id { get; set; }

    public long? BarId { get; set; }

    [ForeignKey(nameof(BarId))]
    [InverseProperty("Foo")]
    public virtual Bar Bar { get; set; }
}

public class Bar
{
    [Key]
    public long Id { get; set; }

    [InverseProperty("Bar")]
    public virtual Foo Foo { get; set;}

}

but if you use net5+ you maybe don't need any attributes or fluent Apis

Upvotes: 1

Related Questions