【问题标题】:EF Code First - 1-to-1 Optional RelationshipEF Code First - 1 对 1 可选关系
【发布时间】: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 *.

【问题讨论】:

    标签: ef-code-first one-to-one


    【解决方案1】:

    一个解决方案是;

    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 将您的键映射到正确的列。

    【讨论】:

    • 这帮助我在尝试配置 0:1 到 0:1 时解决了以下问题 - 此关联的主体端必须使用关系流式 API 或数据注释显式配置。跨度>
    • 我建议您按照惯例包含外键属性 (msdn.microsoft.com/en-us/data/jj679962)。如果每当您创建实体之间的关系时,请通过此键属性而不是实体属性来执行此操作。我发现这种方式不太可能出现某些异常,例如对象状态管理器中的重复键以及更新出错时更有意义的异常。
    • 如何在User 中也使用ContactId 字段?如果我使用上面的代码并在 User 中定义一个 ContactId 字段,它会给我一个错误,说它是一个重复的属性。如何告诉实体框架使用MapKey 定义的列和用户中定义的ContactId 相同。
    • 嗨@gyozokudor,您是否也找到了拥有ContactId字段的方法?谢谢。
    • 我会使用 FK ContactId。见这里:entityframeworktutorial.net/code-first/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多