一尘不染

实体类型MVC5 EF6中的用户

c#

我已经在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();
}

我希望Microsoft以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

我还试图使用asp.net MVC5 EF6中的fluent
api将以下代码添加ApplicationDbContext到此问题映射表中所述的代码中

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


阅读 219

收藏
2020-05-19

共1个答案

一尘不染

以下方法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 });
}
2020-05-19