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

时间:2016-03-15 17:28:22

标签: asp.net-mvc entity-framework asp.net-identity

基本上,我希望有一个可以创建自己故事的用户。

我有这些课程:

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

然后使用Story的contenxt在我的MyDbContext实体上进行迁移。它失败了。

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进行迁移的其他方法时,它会创建一个Story的新表

目前,有效的方法是合并我的背景。像。的东西。

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

但必须有办法单独管理它们,对吧?或者我做错了吗?

1 个答案:

答案 0 :(得分:2)

您无法从另一个上下文中引用实体,或者该上下文也会尝试管理这些实体,从而导致已存在的表出错。您有两种选择:

  1. 如果你实际上不需要两个单独的上下文(即,它们都是Code First,你对一个数据库中的所有内容都很好),那么最好也是最简单的解决方案就是像你一样合并它们。拥有多个上下文没有任何好处,正如您所见,这有很多不利因素。使用多个上下文的唯一理由是,如果您正在处理其他现有数据库。

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

  3. 不幸的是,这是你唯一的选择。