繁体   English   中英

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

[英]Entity Framework - CF - Foreign key mapping to different column

我在项目中使用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表中的外键?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM