it:ad:code_first:howto:define_models:relationships:examples:n-1

IT:AD:EF/CodeFirst:HowTo:Define Models/Relationships/Examples/n-1

    //Many to One, Required
            ////0...*-1:
            modelBuilder.Entity<Invoice>()
                //Ensures Invoice has a Category applied before it is saved:
                .HasRequired(i => i.Category)
                //Ensure (1) Category has many (*) Invoices
                .WithMany(); //1-n

Common is to use n-1 for mandatory reference data, and use an FK property to set it:

Working with an FK is intelligent as it doesn't force you to have to fetch the InvoiceType first, in order to set the Type property – just set the TypeFK to a WellKnown/ value:

    modelBuilder.Entity<Invoice>()
                .HasRequired(m => m.InvoiceType)
                .WithMany()
                .HasForeignKey(m => m.InvoiceTypeFK);

  • /home/skysigal/public_html/data/pages/it/ad/code_first/howto/define_models/relationships/examples/n-1.txt
  • Last modified: 2023/11/04 03:03
  • by 127.0.0.1