When using Entity Framework, I get confused as to where I need to define a relationship between two entities. I feel like whenever I look for examples, I end up finding examples of the same thing from two different perspectives - dependent → principal, as well as principal → dependent.
Given the following entities:
class Foo
{
public int Id { get; set; }
public virtual ICollection<Bar> Bars { get; set; }
}
class Bar
{
public int Id { get; set; }
public Foo Foo { get; set; }
public virtual Baz { get; set; }
}
class Baz
{
public int Id { get; set; }
public Bar Bar { get; set; }
}
We have several scenarios here. Foo
has many Bar
s pointing to it. Baz
has an optional foreign key to Bar
. Baz
can exist without Bar
specified.
Where would I defined these relations? By where, I mean when using fluent API, which entity would these relations be defined in relation to? Maybe to make it more clear, if I were using fluent API and EntityTypeConfiguration
classes for binding, for which entity would these be defined in?
An example of why I'm confused is because I see answers like this one that say that a one-to-one should be defined in the class with the virtual
. So in these entities, the optional one-to-one between Baz
and Bar
would be, or something similar to:
modelBuilder.Entity<bar>()
.HasOptional(f => f.Baz)
.WithRequired(s => s.Bar);
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…