49

我在 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这样的方式实现对象,它可以在其他实体类型中使用,所以我可能做错了什么,因为当我尝试为 Content 实体类型创建控制器时,我得到以下错误:

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 中处理用户。

4

2 回答 2

104

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

 base.OnModelCreating(modelBuilder);

在我的 DbModel

于 2014-07-07T09:48:26.203 回答
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 });
}
于 2013-11-11T21:57:35.100 回答