EF Code First - WithMany()

前端 未结 2 1446
你的背包
你的背包 2020-12-15 07:44

I recently came by the class ManyNavigationPropertyConfiguration , and within that class there I found a method named WithMany()

2条回答
  •  时光取名叫无心
    2020-12-15 08:24

    Note that the choice for a navigation property is on the other side of the target.

    Let's look at an example, even though this specific case might not be the perfect illustrator of my point... If you want to keep track of math tests, and re-use questions, you might have two tables (Tests and Questions) which have a many-to-many relationship; each test has several questions, and each question can appear on several tests. However, you might not ever need to get a collection of tests that a specific question is on - even though you know that questions can appear on more than one test, you aren't interested in which.
    Thus, you use the .WithMany() overload when declaring this, so you get a navigational property to get the questions of a test (theTest.Questions()) but no navigational property the other way (theQuestion.Tests()). But you still need a many-to-many relationship, since both tests and questions can have many of the other.
    I agree that in this specific case this setup might not make sense, but there is certainly cases where it does, and in those cases the .WithMany() overload lets you get by without defining properties (and a lambda expression for each one of them) you'll never need.

提交回复
热议问题