Question

I've made a class in MVC5 where I want the content to have a primary owner and then some editors:

public class Content
{
    public int ID { get; set; }
    public IdentityUser Owner { get; set; }
    public ICollection<IdentityUser> Editors { get; set; }
    public string Title{ get; set; }
    public string Body { get; set; }
}

I have the following code in the database context:

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

    modelBuilder.Entity<Content>()
        .HasOptional(c => c.Editors)
        .WithRequired()
        .WillCascadeOnDelete();

    modelBuilder.Entity<Content>()
        .HasRequired(c => c.Owner)
        .WithOptional()
        .WillCascadeOnDelete();
}

Microsoft ought to have adopted theIdentityUser When I try to create a controller for the Content entity type, I receive the following error, which suggests that I may be doing something incorrectly:

EntityType 'IdentityUserLogin' has no key defined
EntityType 'IdentityUserRole' has no key defined
EntityType: EntitySet 'IdentityUserLogins' is based on type 'IdentityUserLogin' that has no key defined
EntityType: EntitySet 'IdentityUserRoles' is based on type 'IdentityUserRole' that has no key defined

Additionally, I've attempted to add the subsequent code to theApplicationDbContext as stated in this inquiry: Map tables in Asp.net MVC5 EF6 using the fluent API?

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);
    modelBuilder.Entity<IdentityUserLogin>().HasKey<string>(l => l.UserId);
    modelBuilder.Entity<IdentityRole>().HasKey<string>(r => r.Id);
    modelBuilder.Entity<IdentityUserRole>().HasKey(r => new { r.RoleId, r.UserId });
}

I must be making a mistake. How do I manage users in my Content EntityType? Please advise.

1
49
5/23/2017 12:02:19 PM

Accepted Answer

The next approach,OnModelCreating , will establish a practical setting. Though I'm not sure if it is the mapping you seek.

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

    modelBuilder.Entity<Content>()
        .HasMany(c => c.Editors)
        .WithOptional()
        .WillCascadeOnDelete(false);

    modelBuilder.Entity<Content>()
        .HasRequired(c => c.Owner)
        .WithOptional()
        .WillCascadeOnDelete(false);

    modelBuilder.Entity<IdentityUserLogin>().HasKey<string>(l => l.UserId);
    modelBuilder.Entity<IdentityRole>().HasKey<string>(r => r.Id);
    modelBuilder.Entity<IdentityUserRole>().HasKey(r => new { r.RoleId, r.UserId });
}
61
8/15/2015 7:31:21 AM

Popular Answer

I encountered the identical issue and realized I hadn't phoned

 base.OnModelCreating(modelBuilder);

I used a DbModel.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow