Using Entity Framework 5
So, I have a Client. A Client can have many Addresses, but at least one. One of the addresses will also be set as the primary address (required). I tried various mappings, but so far I get an error message when building or when I sow the database.
Customer:
public class Customer { public int CustomerId { get; set;} public String CustomerName { get; set; } public int PrimaryAddressId { get; set; } public virtual CustomerAddress PrimaryAddress { get; set; } public virtual ICollection<CustomerAddress> CustomerAddresses { get; set; } }
Address:
public class CustomerAddress : Address { public int CustomerAddressId { get; set; } public int CustomerId { get; set; } public virtual Customer Customer { get; set; } }
This part of my display is working correctly. He is at CustomerAddress.
this.HasRequired(c => c.Customer) .WithMany(d => d.CustomerAddresses) .HasForeignKey(c => c.CustomerId);
But how do I specify the correct mapping to install PrimaryAddress on Customer? Or is this the wrong approach?
thanks
EDIT - using the answers of Arnolds and LueTM:
This code now works.
Customer:
public class Customer { public int CustomerId { get; set;} public String CustomerName { get; set; } // public int PrimaryAddressId { get; set; } created in mapping public virtual CustomerAddress PrimaryAddress { get; set; } public virtual ICollection<CustomerAddress> CustomerAddresses { get; set; } }
Address:
public class CustomerAddress : Address { public int CustomerAddressId { get; set; } public int CustomerId { get; set; } public virtual Customer Customer { get; set; } }
Customer Mapping:
modelBuilder.Entity<Customer> .HasOptional(c => c.PrimaryAddress) .WithOptionalDependent().Map(m => m.MapKey("PrimaryAddressId")); modelBuilder.Entity<Customer> .HasMany(c => c.CustomerAddresses) .WithRequired(c => c.Customer) .HasForeignKey(c => c.CustomerId) .WillCascadeOnDelete(false);
And I use the repository to make sure that the new address is created first, saved, and then set again as primary and saved. The repository ensures that the primary is "required."
source share