0

I have a Customer that can have a Billing or Shipping address. The Customer has the BillingAddressId and ShippingAddressId that corresponds to an AddressId on the Address table.

I've tried the below setup but keep getting errors:

public class Customer
    [Key]
    public int CustomerId { get; set; }

    [Column("billingAddressId")]
    [ForeignKey("Address")]
    public int BillingAddressId { get; set; }

    [Column("shippingAddressId")]
    public int ShippingAddressId { get; set; }

    public virtual Address BillingAddress { get; set; }

    public virtual Address ShippingAddress { get; set; }

with the Address looking like this:

public class Address
    [Key]
    public int AddressId {get;set;}

    public virtual Customer Customer { get; set; }

My model builder:

    modelBuilder.Entity<Customer>()
            .HasOptional(c => c.BillingAddress)
            .WithOptionalPrincipal(a => a.Customer);

But I keep getting this error The ForeignKeyAttribute on property 'BillingAddressId' on type '...Customer' is not valid. The navigation property 'Address' was not found on the dependent type '...Customer

mche
  • 616
  • 10
  • 16
  • Possible duplicate of [One to zero-or-one with HasForeignKey](https://stackoverflow.com/questions/18719890/one-to-zero-or-one-with-hasforeignkey) – Igor Jul 25 '18 at 18:30
  • One-to-one is not a "Can have" relation like you have stated by using `.HasOptional()`. You might consider having a one-to-many relation between `Customer` and `Address` even though they will have only one billing or shipping address. – Lukas G Jul 25 '18 at 18:37
  • 1
    `[ForeignKey("Address")]` means it is looking for a property called `Address`, not of type `Address`... – Mister Epic Jul 25 '18 at 18:42
  • @MisterEpic I've actually tried "AddressId" and it gave me the same error. – mche Jul 25 '18 at 18:45
  • The FK annotation for property `BillingAddressId` would be `[ForeignKey("BillingAddress")]` to match the corresponding property. – Jasen Jul 25 '18 at 19:00
  • None of those annotations is needed. The default conventions would work just fine. I would also recommend not mixing fluent with annotations. – Steve Greene Jul 25 '18 at 19:12

0 Answers0