Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
313 views
in Technique[技术] by (71.8m points)

c# - Do I define a relationship between two entities on the dependent or the principal?

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 Bars 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

when you use EF as you defined in your classes you already defined you relations. EF has the ability to understand that when you define you navigation properties in Collection in a class

public virtual ICollection<Bar> Bars { get; set; }

that you want one to many Relation.

On the other hand if you add a collection to the other class

public virtual ICollection<Foo> Foos { get; set; }

EF will understand that you want Many to may Relation

same thing will happen if you add an instance of class as property in the other class it will understand that as one to one (or zero to one ) relation.

virtual keyword has nothing to do with your relation as mentioned before, it concerned in lazy, eager loading


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...