【发布时间】:2011-08-26 15:23:16
【问题描述】:
我想使用 EF Code First 在现有数据库中映射可选的一对一关系。
简单架构:
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 *.
【问题讨论】: