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

前端 未结 2 1897
北恋
北恋 2020-11-30 07:06

Here is my Model:

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

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


        
2条回答
  •  迷失自我
    2020-11-30 07:35

    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().HasRequired(x => x.PrimaryMailingAddress)
        .WithMany()
        .HasForeignKey(x => x.PrimaryMailingAddressID)
        .WillCascadeOnDelete(false);
    
    modelBuilder.Entity
    () .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

提交回复
热议问题