简体   繁体   English

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

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

I'm using ASP.NET Identity in my project so my AspNetUser table looks somewhat like this: 我在项目中使用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; }
}

I've added InternalId to use as foreign key in my custom tables because i don't like using Guids everywhere. 我添加了InternalId用作自定义表中的外键,因为我不喜欢到处使用Guid。 So, let's take this table for example: 因此,让我们以该表为例:

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; }
}

Looks good so far, RequestHistory should have navigation property to AspNetUser running on RequestHistory.UserId = AspNetUser.InternalId and vice versa. 到目前为止看起来不错,RequestHistory应该具有在RequestHistory.UserId = AspNetUser.InternalId上运行的AspNetUser的导航属性,反之亦然。 But when i try to run my project i get an error saying: 但是,当我尝试运行我的项目时,出现错误消息:

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'.

Which makes sense because EF is propably trying to match them using the default behaviour but how can i force this association to use InternalId as foreign key from AspNetUser table? 这是有道理的,因为EF可能会尝试使用默认行为来匹配它们,但是我如何才能强制此关联将InternalId用作AspNetUser表中的外键?

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

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

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