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

Summary

1-1 and 1-0..1 relationships are actually trickier than they should be in EF.

In short, EF can't do them unless both have the same Id1)….unless you use a workaround (see below).

That's ok if we're talking about something like:

UserIdUserDetailsIdreferences11

But that's not going to work in cases where we're referencing a table that is shared (and therefore doesn't have an FK in it):

UserIdBillingAddressIdBillingAddressShippingAddressIdShippingAddressAddressIdreferences11references11

In most cases the Entity Framework can infer which type is the dependent and which is the principal in a relationship. However, when both ends of the relationship are required or both sides are optional the Entity Framework cannot identify the dependent and principal. When both ends of the relationship are required, use WithRequiredPrincipal or WithRequiredDependent after the HasRequired method. When both ends of the relationship are optional, use WithOptionalPrincipal or WithOptionalDependent after the HasOptional method.

// Configure the primary key for the OfficeAssignment 
modelBuilder.Entity<OfficeAssignment>() 
    .HasKey(t => t.InstructorID); 
 
modelBuilder.Entity<Instructor>() 
    .HasRequired(t => t.OfficeAssignment) 
    .WithRequiredPrincipal(t => t.Instructor);

If the principal is used in more than one place, then it's not a 1-1 but a -1 or (1,)-1:

 //0..1-1:
        modelBuilder.Entity<User>()
            .HasRequired(i => i.BillingAddress)
            .WithMany() //1-0: as it can be shared with User, don't bind Invoice and Address, so avoid .WithRequired
            .WillCascadeOnDelete(false); //1-0: as it can be shared with User, don't bind Invoice and Address, so avoid 

Working with:

    //Requirements to enable the use of change-tracking POCO Proxies:
    //* Class must be public, non-abstract, non-sealed.
    //* Public *virtual* get/set for all persisted properties.
    //* Collection based Navigation properties must implement ICollection<T>
    //Ref: http://bit.ly/KgJPcU
    public class User
    {
        //...
        //1-1 Required Relationship:
        public virtual int AddressFK { get; set; }
        public virtual Address Address { get; set; }
        //...
    }

    public class Address
    {
        public virtual int Id { get; set; }
        public virtual string Street { get; set; }
        //...
    }

<div warning>


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