简体   繁体   中英

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

I have a Customer Model :

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

    public string Title { get; set; }
}

And I this is what my IdentityModel.cs looks like:

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

After writing that code, I ran enable-migrations , add-migrations and then update-database without any errors occurring.

When I tried to create a MVC 5 controller with views, using Entity Framework , using the model Customer with a new data context class, I got this error :

在此处输入图片说明

Whats going wrong? I haven't changed anything other than the ApplicationUser : IdentityUser class and Customer class.

I'm very new to this so I would appreciate extremely detailed instructions :)

Altough you didn't post the IdentityUserLogin, IdentityUserRole, etc. I can imagine you didn't define primary keys for these classes. Entity Framework requires each and every entity to have a key . You can either follow the convention and name your primary key properties Id or ClassNameId or use data annotations, the Key in particular.

UPDATE

The underlying problem is not related to the foreign key, but to the lack of a primary key.

First, you shouldn't define a property as both Key and ForeignKey. Remove the Key attribute from the UserId and leave just the ForeignKey. Next define an Id property like so:

    public int Id { get; set; }

Entity Framework is intelligent enough to identify it as the Primary Key. Do this in all your entities, update the database and you're good to go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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