实体框架 - CF - 外键映射到不同的列

时间:2016-05-05 21:29:16

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

我在我的项目中使用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添加为自定义表中的外键,因为我不喜欢在任何地方使用Guids。所以,让我们以此表为例:

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表中的外键?

1 个答案:

答案 0 :(得分:0)

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