Entity Framework Code First: How can I create a One-to-Many AND a One-to-One relationship between two tables?
Asked Answered
T

2

19

Here is my Model:

public class Customer
{
    public int ID { get; set; }

    public int MailingAddressID { get; set; }
    public virtual Address MailingAddress { get; set; }

    public virtual ICollection<Address> Addresses { get; set; }
}

public class Address
{
    public int ID { get; set; }

    public int CustomerID { get; set; }
    public virtual Customer Customer { get; set; }
}

A customer can have any number of addresses, however only one of those addresses can be a mailing address.

I can get the One to One relationship and the One to Many working just fine if I only use one, but when I try and introduce both I get multiple CustomerID keys (CustomerID1, CustomerID2, CustomerID3) on the Addresses table. I'm really tearing my hair out over this one.

In order to map the One to One relationship I am using the method described here http://weblogs.asp.net/manavi/archive/2011/01/23/associations-in-ef-code-first-ctp5-part-3-one-to-one-foreign-key-associations.aspx

Tomblin answered 18/3, 2011 at 0:39 Comment(0)
T
19

I've struggled with this for almost the entire day and of course I wait to ask here just before finally figuring it out!

In addition to implementing the One to One as demonstrated in that blog, I also then needed to use the fluent api in order to specify the Many to Many since the convention alone wasn't enough with the One to One relationship present.

modelBuilder.Entity<Customer>().HasRequired(x => x.PrimaryMailingAddress)
    .WithMany()
    .HasForeignKey(x => x.PrimaryMailingAddressID)
    .WillCascadeOnDelete(false);

modelBuilder.Entity<Address>()
    .HasRequired(x => x.Customer)
    .WithMany(x => x.Addresses)
    .HasForeignKey(x => x.CustomerID);

And here is the final model in the database: enter image description here

Tomblin answered 18/3, 2011 at 0:58 Comment(0)
E
2

I know you're trying to figure out the Entity Framework way of doing this, but if I were designing this I would recommend not even wiring up MailingAddress to the database. Just make it a calculated property like this:

public MailingAddress {
   get {
      return Addresses.Where(a => a.IsPrimaryMailing).FirstOrDefault();
   }
}
Electrician answered 18/3, 2011 at 0:49 Comment(1)
This however creates the problem of having to maintain that only one Address has IsPrimaryMailing = true which can easily go wrong.Wexford

© 2022 - 2024 — McMap. All rights reserved.