0

I'm pretty new to Entity Framework and want to create a (personal) quick reference manual. The goal with it is to give myself some really short code first examples with different cardinalities:

  • one-to-one
  • one-to-many
  • many-to-many

Here is what I have done so far: enter image description here First of all, I am very well aware that there are several threads on this particular subject out there (I've read a lot, many with confusing opposite statements). Second, I'm only interested in [Data Annotation]-style (not in any kind of fluent APIs!).

Many sources out there confuses me, but just to make my question short: Is it really necessary to ever use the [System.ComponentModel.DataAnnotations.Schema.ForeignKey]-attribute (I mean in my one-to-many and many-to-many code examples)?

Edit 1: Moho provided me with a link and I updated my model (one-to-one) according to what I understood from the information found there: One-to-One

Should I have the same string in [ForeignKey("<nav prop1>")] as which I have in the name of my virtual property public virtual Locker <nav prop2> { get; set; }? I. e. is <nav prop1> = <nav prop2>?

Community
  • 1
  • 1
Hauns TM
  • 1,909
  • 2
  • 22
  • 38

1 Answers1

1

Your 1-1 example is not accurate - technically N Lockers can refer to a single Student, and N Students can refer to a single Locker, but EF will throw an InvalidOperationException with message "Unable to determine the principal end of an association"

Use a shared primary key to enforce 1-1 relationship (attribute the PK field with both [Key] and [ForeignKey("<nav prop>")]

More reading on the topic here

Moho
  • 15,457
  • 1
  • 30
  • 31