使用多上下文应用程序的自定义 ASPNET 标识一对多关系

Custom ASPNET Identity one to many relationship using multiple context application

基本上,我想要一个可以创建自己故事的用户。

我有这些 类:

public class ApplicationUser : IdentityUser
{
  public string DisplayedName { get; set; }
}

public class Story
{
  public int Id { get; set; }
  public string Content { get; set; }
}

它们在不同的上下文中进行管理,因此它们的迁移也是如此。像这样。

public class MyDbContext : DbContext
{
  public DbSet<Story> Stories { get; set; }
}

public class IdentityContext : IdentityDbContext<ApplicationUser>
{
}

当我尝试添加一个迁移然后单独更新它们时,它工作正常但是当我尝试在我的应用程序用户中添加故事集时。

public class ApplicationUser : IdentityUser
{
  public string DisplayedName { get; set; }
  public virtual ICollection<Story> Stories { get; set; }
}

public class Story
{
  public int Id { get; set; }
  public string Content { get; set; }
  public string WrittenById { get; set; }
  public virtual ApplicationUser WrittenBy { get; set; }
}

public class StoryMap : EntityTypeConfiguration<Story>
{
  public StoryMap()
  {
    HasOptional(s => s.WrittenBy)
      .WithMany(s => s.Stories)
      .HasForeignKey(s => s.WrittenById)
      .WillCascadeOnDelete(false);
  }
}

然后使用 MyDbContext 的上下文对我的 Story 实体进行迁移,但它没有说。

Data.IdentityUserLogin: : EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType.
Data.IdentityUserRole: : EntityType 'IdentityUserRole' has no key defined. Define the key for this EntityType.
IdentityUserLogins: EntityType: EntitySet 'IdentityUserLogins' is based on type 'IdentityUserLogin' that has no keys defined.
IdentityUserRoles: EntityType: EntitySet 'IdentityUserRoles' is based on type 'IdentityUserRole' that has no keys defined.

但是当我尝试使用 IdentityContext 进行迁移的另一种方法时,它会创建一个新的 table of Story

目前,有效的方法是合并我的上下文。有点像。

public class MyDbContext : IdentityDbContext<ApplicationUser>
{
  public DbSet<Story> Stories { get; set; }
}

但一定有办法分别管理它们,对吧?还是我做错了?

您不能在另一个上下文中引用一个上下文中的实体,否则该上下文也会尝试管理这些实体,从而导致有关已存在的表的错误。您有两个选择:

  1. 如果您实际上 不需要 两个单独的上下文(即,它们都是代码优先,并且您可以将所有内容都放在一个数据库中),那么最好和最简单的解决方案就是像您所做的那样合并它们。拥有多个上下文没有任何好处,而且如您所见,还有很多不利之处。使用多个上下文的唯一充分理由是您正在处理其他现有数据库。

  2. 创建一个简单的列来存储相关的 id(不是外键)。你失去了拥有真正外键的优化和延迟加载的能力,但你至少仍然可以通过这种方式将事情联系起来。本质上,您只需将此 属性 设置为其他上下文中相关对象的 ID。然后,当您需要检索该对象时,您只需使用该 ID 对其他上下文发出查询。换句话说,您只需手动获取对象即可。

不幸的是,这是您唯一的选择。