0

我正在尝试建立一对一的关系,导航属性位于一侧(MVC4、EF5、代码优先)。

public class User {

  public int UserId { get; set; } //PK

  public int RankId { get; set; } //FK

  public virtual Rank { get; set; } //Navigation

}

public class Rank {

  public int RankId { get; set; }

}

配置:

 public class RankConfiguration : EntityTypeConfiguration<Rank>
{
    public RankConfiguration()
    {
      HasKey(e => e.RankId);
      Property(e => e.RankId)
        .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
    }
}

public class UserConfiguration : EntityTypeConfiguration<User>
{
    public UserConfiguration ()
    {
      // PK
      HasKey(e => e.UserId);

      Property(e => e.RankId)
        .IsRequired();

      HasRequired(e => e.Rank)
        .WithRequiredDependent()
        .WillCascadeOnDelete(true);
    }
}

对于我所看到的(以及我所知道的很少),db 是正确生成的,但我收到了这个错误:

ReferentialConstraint 中的依赖属性映射到存储生成的列。列:“用户 ID”。

在第一次尝试中,我正在考虑创建一个连接表(参考此处EF5 Fluent API one-to-one without navigator),不知道是否是个好主意,但我无法使用 fluent API。

我不知道为什么以及出了什么问题..有什么帮助吗?提前谢谢了

更新

第一次尝试@soadyp评论 后,我尝试配置一个一对一的连接表

HasRequired(e => e.Rank)
    .WithRequiredDependent()
    .Map(m =>
    {
      m.ToTable("UserRank");
      m.MapKey("RankId");
    })
    .WillCascadeOnDelete(true);

但是当我尝试迁移时出现此错误:

The specified table 'UserRank' was not found in the model. 
Ensure that the table name has been correctly specified.

第二次尝试阅读此http://weblogs.asp.net/manavi/archive/2011/04/14/associations-in-ef-4-1-code-first- 后,我可能正在做一个简单的工作太复杂了part-3-shared-primary-key-associations.aspx我就是这样改的

  HasRequired(e => e.Rank)
    .WithOptional()
    .WillCascadeOnDelete(true);

一切都很好,但是 UserId PK 没有设置为身份(当我插入一行时有明显的问题)。如果我将其指定为身份:

  Property(e => e.UserId)
    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

我收到以下错误:

Cascading foreign key 'FK_dbo.Users_dbo.Ranks_UserId' cannot be created where 
the referencing column 'Users.UserID' is an identity column.
Could not create constraint. See previous errors.
4

2 回答 2

1

1:1 code first in EF requires the dependent table to have the SAME primary key. Otherwise what you want to do will work.

EDIT Similar SO post Code First and Fluent API one to one relationship

Here is the MS EF site sample. http://msdn.microsoft.com/en-us/data/jj591620#RequiredToRequired

于 2013-02-21T08:13:23.960 回答
1

好的,所以我复制了您的代码并进行了尝试,我的答案有多个部分:

  1. 使用您当前的配置,生成的数据库有些混乱,在用户表中看到“UserId”正在成为 FK(我不知道为什么真的)所以“RankId”只是成为一个普通的整数属性(它不是一个键),所以我认为这是触发您提到的关于引用约束的第一个异常,因为如果您考虑一下,数据库知道“UserId”是主键,同时它是外键但是“UserId”(即“RankId”)引用的实际密钥不是数据库生成的,因此数据库假设如何找出所有这些信息。
  2. 现在可能有一个“正确的配置来解决这个问题,但我找不到,所以为了解决这个问题,我删除了流畅的配置,并且实体框架按照惯例创建了所有内容,它做得很好(它发现“RankId”在用户类实际上是一个外键)。

一个建议,尝试查看配置有什么问题,每次更改都使用 SQL Server Management Studio 或任何其他工具,您必须检查生成的数据库架构以确保它是您希望的,另外,如果您不需要配置只是不要使用它。

于 2013-02-22T01:20:12.557 回答