[英]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. 如果我只使用一个,我可以得到One to One关系,One to Many工作得很好,但是当我尝试介绍两者时,我在Addresses表上获得了多个CustomerID键(CustomerID1,CustomerID2,CustomerID3)。 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 为了映射一对一的关系,我使用这里描述的方法http://weblogs.asp.net/manavi/archive/2011/01/23/associations-in-ef-code-first-ctp5-part- 3,一到一个外键,associations.aspx
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. 除了在博客中展示的实现一对一之外,我还需要使用流畅的api来指定多对多,因为单独的约定不足以存在一对一的关系。
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. 我知道你正在试图找出实体框架这样做的方法,但如果我正在设计这个,我建议甚至不要将MailingAddress连接到数据库。 Just make it a calculated property like this:
只需将它设为这样的计算属性:
public MailingAddress {
get {
return Addresses.Where(a => a.IsPrimaryMailing).FirstOrDefault();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.