实体类型MVC5 EF6中的用户

时间:2013-11-11 18:40:23

标签: c# asp.net entity-framework asp.net-mvc-5 asp.net-identity

我在MVC5中创建了一个类,我想要内容的主要所有者,然后我想为内容编写一些编辑器:

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

在数据库上下文中,我有以下代码:

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

我希望微软以这样的方式实现IdentityUser对象,它可以在其他实体类型中使用,所以我可能做错了,因为当我尝试为其创建控制器时内容实体类型,我收到以下错误:

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

我还尝试将以下代码添加到ApplicationDbContext,如此问题Map tables using fluent api in asp.net MVC5 EF6?中所述:

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

我一定是做错了。请告诉我如何处理Content EntityType中的用户。

2 个答案:

答案 0 :(得分:105)

我有同样的问题,我发现我没有打电话

 base.OnModelCreating(modelBuilder);

在我的DbModel

答案 1 :(得分:61)

以下方法OnModelCreating将创建工作上下文。不确定它是否是您想要的映射。

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