簡體   English   中英

從ASP.Net MVC 5 Identity添加外鍵時發生錯誤?

[英]Error occurs when adding foreign key from ASP.Net MVC 5 Identity?

我有一個客戶模型:

public class Customer
{
    [Key, ForeignKey("ApplicationUser")]
    public string UserId { get; set; }
    public virtual ApplicationUser ApplicationUser { get; set; }

    public string Title { get; set; }
}

這就是我的IdentityModel.cs的樣子:

public class ApplicationUser : IdentityUser
{
    public virtual Customer Customer { get; set; }

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }
}

ApplicationDbContext:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }

    //new
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
    }
}

編寫完該代碼后,我運行了enable-migrationsadd-migrationsupdate-database,沒有發生任何錯誤。

當我嘗試使用Entity Framework ,使用帶有新數據上下文類的Customer模型,使用視圖創建MVC 5控制器時 ,出現以下錯誤:

在此處輸入圖片說明

怎么了 除了ApplicationUser:IdentityUser類和Customer類之外,我沒有進行任何其他更改。

我對此很陌生 ,所以我將不勝感激非常詳細的說明:)

盡管您沒有發布IdentityUserLogin,IdentityUserRole等。我可以想象您沒有為這些類定義主鍵。 實體框架要求每個實體都具有一個密鑰 您可以遵循約定並命名主鍵屬性IdClassNameId,也可以使用數據注釋,尤其是Key。

UPDATE

潛在的問題與外鍵無關,而與缺少主鍵有關。

首先,您不應同時將屬性定義為Key和ForeignKey。 從UserId中刪除Key屬性,僅保留ForeignKey。 接下來定義一個Id屬性,如下所示:

    public int Id { get; set; }

實體框架足夠智能,可以將其識別為主鍵。 在所有實體中執行此操作,更新數據庫,一切順利。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM