it:ad:code_first:entities:relationships:1-0..1

IT:AD:Code First:Entities:Relationships:1:0..1

  • You have an Invoice and a User and Address.
  • You want a 1-1..0 relationship between User and Address.
    • ie, a User may or may not have a (non-shared) Address,
  • You want a Refererence Navigation Property from User to Address
  • You do not want a Reference Navigation Property from Address back to User
  • As it's not a IT:AD:Code First:Entities:Relationships:1-1 relationship there's no reason to tie the two id's together.

From MS Doc (http://msdn.microsoft.com/en-US/data/jj591620):

// Map one-to-zero or one relationship
modelBuilder.Entity<OfficeAssignment>()
  .HasRequired(t => t.Instructor)
  .WithOptional(t => t.OfficeAssignment);

//Note that if Address does not follow convention and 
//have a field called "AddressID" (eg: here it's 'UserID') 
//have to define key manually
modelBuilder.Entity<Address>()
.HasKey(t => t.UserID);
 

Exactly same answer as IT:AD:Code First:Entities:Relationships:1-1, just that you replace .HasRequired with .HasOptional

            modelBuilder.Entity<User>()
                .HasOptional(i=>i.BillingAddress)
                .WithMany();

That said…the above will not account for you using a custom FK.

In which case you need (neato):

//Take it out of the model
 modelBuilder.Entity<User>().Ignore(x=>ContactID);

//So you can add it as follows...
 modelBuilder.Entity<User>()
            .HasOptional<Contact>(u => u.Contact)
            .WithOptionalDependent(c => c.User).Map(p => p.MapKey("ContactID"));

  • /home/skysigal/public_html/data/pages/it/ad/code_first/entities/relationships/1-0..1.txt
  • Last modified: 2023/11/04 02:19
  • by 127.0.0.1