WithOptionalDependent vs WithOptionalPrinciple - Definitive Answer?

c# ef-code-first entity-framework

Question

I reasoned that getting a clear explanation of when to utilize WithOptionalDependent and WithOptionalPrincipal could be useful. The documentation for the two functions is a little hazy, so I often have to combine answers from different Stack Overflow answers and other websites to be certain that the relationship is heading in the right direction.

According to MSDN, the WithOptionalDependent is as follows:

Configures the relationship to be optional:optional without a navigation property on the other side of the relationship. The entity type being configured will be the dependent and contain a foreign key to the principal. The entity type that the relationship targets will be the principal in the relationship.

What it says about WithOptionalPrincipal is as follows:

Configures the relationship to be optional:optional without a navigation property on the other side of the relationship. The entity type being configured will be the principal in the relationship. The entity type that the relationship targets will be the dependent and contain a foreign key to the principal.

The section that usually baffles me is "The entity type being configured" (and I assume others).

In this instance:

class MyEntityA
{
    [Key]
    public int Id { get; set; }
    public int BId { get; set; }
    [ForeignKey("BId")]
    public MyEntityB B { get; set; }
}

class MyEntityB
{
    [Key]
    public int Id { get; set; }
}

modelBuilder.Entity<MyEntityA>().HasOptional(a => a.B).WithOptionalDependent();

refers to "The entity type being configured"MyEntityA or MyEntityB ? I'm assuming the first option.

If that's the case, give me an instance of when you'd useWithOptionalPrincipal ?

In my code example, I believe it really ought to beWithMany neither of the WithOptional choices, either. Obviously, I'm still perplexed!

Both of these routines have overrides that take the navigation property and take it in the opposite direction. Please correct me if I'm wrong, but I presume those overloads don't affect those conclusions.

I'm hoping that this will also benefit a wider audience.

1
48
12/28/2015 8:38:34 PM

Popular Answer

ZZZ_tmp
14
3/25/2019 10:09:44 AM


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