我正试图在Institution
和Address
表之间创建一个到零或一个关系。我基本上期待AddressId
列将在关系建立后包含在Institution
表中。如何在实体框架代码优先中创建一个到零或一个关系?
这是我的代码:
public class Institution
{
public int InstitutionId { get; set; }
public string Name { get; set; }
//1 to 1 with Address
public virtual Address Address { get; set; }
//one--to-many with Professor
public virtual IList<Professor> Profesors { get; set; }
}
public class Address
{
public int AddressId { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public int StateId { get; set; }
public int CountryId { get; set; }
public string ZipCode { get; set; }
public virtual Institution Institution { get; set; }
}
在上下文类:
modelBuilder.Entity<Institution>()
.HasOptional(i => i.Address)
.WithRequired(ad => ad.Institution);
当我看到数据库图表我看到这两个表之间建立关系 - 与黄色的关键该行的两端 - 但AddressId
列都不包含在Institution
表中,InstitutionId
也不包含在Address
表中。
感谢
请参阅[共享主键关联](http://weblogs.asp.net/manavi/associations-in-ef-4-1-code-first-part-3-shared-primary-key-协会) –