C# 如何首先在实体框架代码中创建一对零或一关系?
我试图在C# 如何首先在实体框架代码中创建一对零或一关系?,c#,entity-framework,C#,Entity Framework,我试图在机构和地址表之间创建一对零或一的关系。我基本上希望在建立关系后,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; se
机构
和地址
表之间创建一对零或一的关系。我基本上希望在建立关系后,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; }
}
公共类机构
{
公共int机构ID{get;set;}
公共字符串名称{get;set;}
//1对1,带地址
公共虚拟地址{get;set;}
//一对多和教授在一起
公共虚拟IList教授{get;set;}
}
公共课堂演讲
{
public int AddressId{get;set;}
公共字符串地址1{get;set;}
公共字符串地址2{get;set;}
public int StateId{get;set;}
public int CountryId{get;set;}
公共字符串ZipCode{get;set;}
公共虚拟机构{get;set;}
}
在上下文类中:
modelBuilder.Entity<Institution>()
.HasOptional(i => i.Address)
.WithRequired(ad => ad.Institution);
modelBuilder.Entity()
.has可选(i=>i.Address)
.需要(ad=>ad.Institution);
当我看到数据库图时,我看到这两个表之间建立了一种关系——在这行的两端都有一个黄色的键——但是AddressId
列既不包括在Institution
表中,也不包括InstitutionId
表中
感谢基本上,您的目的是在EF为您提供a时创建一个,因为EF 6不支持前者,而共享主键关联是EF 6在涉及1:1实体关系时支持的唯一关联类型 除了您现在拥有的选项外,您还有:
见Thanky you@MortezaManavi,关于EF7的信息对我来说也是新的++1不客气。如果您决定尝试使用EF Core上的1:1 Associations,请注意它当前存在一个bug,我在这里解释了: