簡體   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