我想使用EF Code First在现有数据库中映射可选的1对1关系。
简单架构:
User
Username
ContactID
Contact
ID
Name
显然ContactID加入了Contact.ID。 ContactID字段可以为空,因此关系是可选的 - 0或1,绝不多。
那么如何使用现有架构在EF Code First中指定此关系?
这是我到目前为止所尝试的内容:
public class User
{
[Key]
public string Username { get; set; }
public int? ContactID { get; set; }
[ForeignKey("ContactID")]
public virtual Contact Contact { get; set; }
}
public class Contact
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
public virtual User User { get; set; }
}
modelBuilder.Entity<User>().HasOptional<Contact>(u=> u.Contact)
.WithOptionalDependent(c => c.User);
我得到以下例外:
System.Data.Edm.EdmAssociationEnd: : Multiplicity is not valid in Role
'User_Contact_Source' in relationship 'User_Contact'. Because the Dependent
Role properties are not the key properties, the upper bound of the multiplicity
of the Dependent Role must be *.
答案 0 :(得分:42)
一种解决方案是;
public class User
{
[Key]
public string Username { get; set; }
public virtual Contact Contact { get; set; }
}
public class Contact
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
public virtual User User { get; set; }
}
modelBuilder.Entity<User>()
.HasOptional<Contact>(u => u.Contact)
.WithOptionalDependent(c => c.User).Map(p => p.MapKey("ContactID"));
您只在POCO中设置了导航对象,而是使用流畅的API将您的密钥映射到正确的列。