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

北战南征 提交于 2019-11-27 04:24:29

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:

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();
   }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!