One-to-One optional relationship with both ends optional and both FKs

.net ef-code-first entity-framework entity-framework-6

Question

This is what I'm doing: 1-to-1 Optional Relationship with EF Code First

And this is how my relationships are set up:

public class Review {
    [Key]
    public int ReviewId { get; set; }

    public virtual Payment Payment { get; set; }
}

public class Payment {
    [Key]
    public int PaymentId { get; set; }

    [ForeignKey("Review")]
    public int? ReviewId { get; set; }
    public virtual Review Review { get; set; }
}

    public class ReviewConfiguration : EntityTypeConfiguration<Review>
{
    public ReviewConfiguration()
    {
        // One-to-One Optional
        HasOptional<Payment>(s => s.Payment).WithOptionalDependent(s => s.Review).Map(s => s.MapKey("PaymentId"));
    }
}

And I only ever receive ONE of the keys mapped as an optional FK; the other is never valid:

enter image description here

Why am I misusing this?

I've seen several strange, hacky methods that don't fit what I'm looking for, like making empty lists, etc. I'm trying to find the perfect strategy here; it has had to exist, right?

Update

I now use the above, however it really stinks because I have to hunt for the [pseudo-FK] ReviewId every time I need to see or delete the Review when I have the Payment on hand.

1
2
5/23/2017 11:59:40 AM

Accepted Answer

ZZZ_tmp
7
5/23/2017 12:31:42 PM

Popular Answer

Your models must have mistakes (2 ReviewId fields in payment?). Additionally, avoid adding any connection properties to the fluent version to further complicate things. IAC, consider the following:

public class Review {
    public int ReviewId { get; set; }

    public int? PaymentId { get; set; }
    public virtual Payment Payment { get; set; }
}

public class Payment {
    public int PaymentId { get; set; }

    public int? ReviewId { get; set; }
    public virtual Review Review { get; set; }
}

public class ReviewConfiguration : EntityTypeConfiguration<Review>
{
    public ReviewConfiguration()
    {
        HasOptional(r => r.Payment)
            .WithMany()
            .HasForeignKey(r => r.PaymentId);
    }
}

public class PaymentConfiguration : EntityTypeConfiguration<Payment>
{
    public PaymentConfiguration()
    {
        HasOptional(p => p.Review)
            .WithMany()
            .HasForeignKey(p => p.ReviewId);
    }
}


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