Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
559 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...