EF代码优先 - 1对1可选关系

Chr*_*ini 26 one-to-one ef-code-first

我想使用EF Code First在现有数据库中映射可选的1对1关系.

简单架构:

User
 Username
 ContactID

Contact
 ID
 Name
Run Code Online (Sandbox Code Playgroud)

显然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);
Run Code Online (Sandbox Code Playgroud)

我得到以下例外:

  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 *.
Run Code Online (Sandbox Code Playgroud)

Per*_*Per 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"));
Run Code Online (Sandbox Code Playgroud)

您只在POCO中设置导航对象,而是使用流畅的API将密钥映射到正确的列.

  • 我怎样才能在`User`中使用`ContactId`字段?如果我使用上面的代码并在User中定义一个`ContactId`字段,它会给我一个错误,说它是一个重复的属性.如何告诉实体框架使用`MapKey`定义的列和User中定义的`ContactId`是相同的. (9认同)
  • 您好@gyozokudor您是否找到了使用ContactId字段的方法?谢谢. (3认同)