【问题标题】:How to tell EntityFramework 5.0 that there's a one-to-one association between two entities?如何告诉 EntityFramework 5.0 两个实体之间存在一对一的关联?
【发布时间】:2014-06-09 09:25:46
【问题描述】:

我可以在设计视图中进入 EDMX 并更新关联的基数(1-、0- 等),但我想知道这样做是否可以场景。

我有这两张表,比方说:

User
-----
Id


UserProfile
-------------
Id
UserId
Stuff

单个用户可能只有一个个人资料。因此,我在UserProfile 表中的UserId 列中设置了唯一约束。此外,UserProfile.Id 被定义为引用 User.Id 的外键。

但是,在实体框架模型中,我得到以下信息:

class User
{
  ICollection<UserProfile> UserProfiles { get; set; }
}

起初,UserProfile 表没有任何自己的主键,如下所示:

UserProfile
--------------
UserId
Stuff

但 EntityFramework 将其设为只读,因为它需要在您希望使其可写的每个表上都有一个主键。所以,我也在UserProfile 表中添加了一个Id 列。

更新

我尝试在设计器的 EDMX 中设置 User 表和 UserProfile 表之间关联的多重性/基数。但是,我收到此错误,建议我应该将其恢复为原来的状态,即一对多关系。

Running transformation: Multiplicity is not valid in Role 'UserBasicProfile' 
in relationship 'FK_UserBasicProfile_User'. Because the Dependent Role 
properties are not the key properties, the upper bound of the multiplicity 
of the Dependent Role must be *.

【问题讨论】:

    标签: entity-framework entity-framework-5


    【解决方案1】:

    我找到了办法。好吧,我所追求的不是纯粹的 1-1 关系,而是 1-0..1 的关系,实际上是一对一的关系。

    如果你像我在我的问题中描述的那样落入这个陷阱,你可以这样做:

    1) 从 dependent 表中删除 Id 字段,在本例中为 UserProfile 表。因此,不要给它一个单独的主键。

    2) 相反,将从属表中的外键标记为它自己的主键。在这种情况下,将UserId 字段本身标记为UserProfile 表的主键。

    除了这两个之外,我假设,正如我在问题中概述的那样,您在 authority(本例中为 User 表)和dependent 表(本例中为 UserProfile 表)。

    所以,你的新表结构应该是这样的:

    User
    ------
    Id
    
    
    UserProfile
    -------------
    UserId (foreign key, and also the primary key of this UserProfile table)
    Stuff
    

    实体框架随后将识别这种 1-0..1 关系。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-20
      • 1970-01-01
      • 2012-11-02
      • 1970-01-01
      • 2015-05-14
      • 1970-01-01
      • 2014-11-27
      相关资源
      最近更新 更多