【问题标题】:Entity Framework - CF - Foreign key mapping to different column实体框架 - CF - 外键映射到不同的列
【发布时间】:2016-05-06 06:13:42
【问题描述】:

我在我的项目中使用 ASP.NET Identity,所以我的 AspNetUser 表看起来有点像这样:

public class AspNetUser
{
    [Key, Index(IsUnique = true), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid Id { get; set; }

    [Index(IsUnique = true), DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int InternalId { get; set; }

    // Navigation properties
    public virtual ICollection<RequestHistory> RequestHistories { get; set; }
}

我已添加 InternalId 以在我的自定义表中用作外键,因为我不喜欢到处使用 Guid。所以,我们以这张表为例:

public class RequestHistory
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public int? UserId { get; set; }

    // Navigation properties
    [ForeignKey("UserId")]
    public virtual AspNetUser User { get; set; }
}

到目前为止看起来不错,RequestHistory 应该具有在 RequestHistory.UserId = AspNetUser.InternalId 上运行的 AspNetUser 的导航属性,反之亦然。但是当我尝试运行我的项目时,我收到一条错误消息:

RequestHistory_User_Target_RequestHistory_User_Source: : The types of all properties in the Dependent Role of a referential constraint must be the same as the corresponding property types in the Principal Role. The type of property 'UserId' on entity 'RequestHistory' does not match the type of property 'Id' on entity 'AspNetUser' in the referential constraint 'RequestHistory_User'.

这是有道理的,因为 EF 可能会尝试使用默认行为来匹配它们,但是我如何强制此关联使用 InternalId 作为 AspNetUser 表中的外键?

【问题讨论】:

  • 请查看 Stack Overflow 上的以下问题stackoverflow.com/questions/27609023/…
  • 谢谢你的回答,但你是不是暗示因为The Entity Framework currently only supports basing referential constraints on primary keys所以不能做?

标签: c# entity-framework ef-code-first entity-framework-6


【解决方案1】:

您需要在 RequestHistory 上将外键设置为 InternalId 而不是 UserId。

【讨论】:

  • 我希望它会这么简单。 ForeignKey 属性与同一个类相关,因此通过在 User 对象上指定 ForeignKey ,我所做的就是告诉 EF 将实际键放在 UserId 属性中。但是要仔细检查,我已将 ForeignKey 更改为 InternalId 并且正如预期的那样,我得到了 The ForeignKeyAttribute on property 'User' on type 'RequestHistory' is not valid. The foreign key name 'InternalId' was not found on the dependent type 'RequestHistory'. The Name value should be a comma separated list of foreign key property names.
猜你喜欢
  • 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
相关资源
最近更新 更多