实体框架代码第一:如何在两个表之间创建一对多与一对一的关系?
这是我的模型:
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.
我可以获得一对一的关系,一对多的工作只要我使用一个,但是当我尝试引入两者我在地址表上获得了多个CustomerID密钥(CustomerID1,CustomerID2,CustomerID3)。
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.
为了映射一对一关系,我使用这里描述的方法 http://weblogs.asp.net/manavi/archive/2011/01/23/associations-in-ef-code-first-ctp5-part-3-one-to-one-foreign-key- associations.aspx
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
我几乎整天都在努力,当然我等待问在这之前,最终弄清楚了!
I've struggled with this for almost the entire day and of course I wait to ask here just before finally figuring it out!
除了在博客中演示的一对一之外,我还需要使用流畅的api来指定一般来说,由于一对一的关系不存在,所以多对多是不够的。
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: