C#C
C#3mo ago
AlisterKB

Fluent API: defining one to many

Models classes :
C#
   public class Customer
 {
     public int Id { get; set; }
     public string Name { get; set; }
     public string Contact { get; set; }
     public ICollection<ShippingAddress> ShippingAddressNavigation { get; set; } = new List<ShippingAddress>();
 }
   public class ShippingAddress
  {
      public int Id { get; set; }
      public string Address { get; set; }
      public int CustomerId { get; set; }
      public Customer CustomerNavigation { get; set; }

  }

Mappings:
C#
 public class CustomerMapping : IEntityTypeConfiguration<Customer>
 {
     public void Configure(EntityTypeBuilder<Customer> builder)
     {
         builder.ToTable("customers");
         builder.HasKey(c => c.Id);
         builder.HasMany<ShippingAddress>(c => c.ShippingAddressNavigation).WithOne(s => s.CustomerNavigation).HasForeignKey(s => s.CustomerId);
     }
 }
 
  public class ShippingAddressMapping : IEntityTypeConfiguration<ShippingAddress>
  {
      public void Configure(EntityTypeBuilder<ShippingAddress> builder)
      {
          builder.ToTable(nameof(ShippingAddress));
          builder.HasKey(s=>s.Id);
          builder.HasOne<Customer>(S => S.CustomerNavigation).WithMany(c => c.ShippingAddressNavigation).HasForeignKey(a=>a.CustomerId);
      }
  }

So I've commented out one, each time and ran the database, keeping one at the time,
builder.HasMany<ShippingAddress>(c => c.ShippingAddressNavigation).WithOne(s => s.CustomerNavigation).HasForeignKey(s => s.CustomerId);
builder.HasOne<Customer>(S => S.CustomerNavigation).WithMany(c => c.ShippingAddressNavigation).HasForeignKey(a=>a.CustomerId);
appears i get the same results
so here are my questions:
  1. is there any difference between defining the relationship from Customer or ShippingAddress that I've failed to observe? Am I right to assume I'm achieving the same thing just from different side of the relationship?
  2. is one way better in terms of anything (convention, readability, etc)?
Was this page helpful?