EF代码优先-一对一的可选关系

| 我想使用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 *.
    
已邀请:
一种解决方案是:
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中设置导航对象,而是使用fluent API将密钥映射到正确的列。     

要回复问题请先登录注册